我想在Java中从系统剪贴板制作一个粘贴板。我该怎么做?
虽然机器人类可以工作,但直接使用系统剪贴板更为简洁,像这样:
private void onPaste(){
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable t = c.getContents(this);
if (t == null)
return;
try {
jtxtfield.setText((String) t.getTransferData(DataFlavor.stringFlavor));
} catch (Exception e){
e.printStackTrace();
}//try
}//onPaste
try
{
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_V);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_V);
}
catch(Exception e)
{
}
试试这个
public static void type(String characters) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection stringSelection = new StringSelection( characters );
clipboard.setContents(stringSelection, instance);
//control+V is for pasting...
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
你也可以尝试使用Clipboard类。
public static void getClipboardContents() {
String result = "";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//odd: the Object param of getContents is not currently used
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText =
(contents != null) &&
contents.isDataFlavorSupported(DataFlavor.stringFlavor)
;
if (hasTransferableText) {
try {
result = (String)contents.getTransferData(DataFlavor.stringFlavor);
System.out.print(result);
}
catch (UnsupportedFlavorException | IOException ex){
System.out.println(ex);
ex.printStackTrace();
}
}
}
系统剪贴板中的内容存储在result字符串变量中。 解决方案来自:http://www.javapractices.com/topic/TopicAction.do?Id=82
java.awt.Toolkit.getSystemClipboard()
和Clipboard
类吗?你的问题具体是什么? - EboMike