1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable;
public class Main {
public static void main(String[] args) throws InterruptedException { setClipboardString("Hello System Clipboard!");
String text = getClipboardString(); System.out.println("text: " + text); }
public static void setClipboardString(String text) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable trans = new StringSelection(text); clipboard.setContents(trans, null); }
public static String getClipboardString() { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable trans = clipboard.getContents(null);
if (trans != null) { if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String text = (String) trans.getTransferData(DataFlavor.stringFlavor); return text; } catch (Exception e) { e.printStackTrace(); } } }
return null; }
}
|