如何使用系统剪贴板从java中粘贴?

时间:2011-07-09 00:40:58

标签: java clipboard

我想在java中从系统剪贴板中粘贴。我该怎么做?

6 个答案:

答案 0 :(得分:9)

虽然机器人类可以工作,但它不像直接使用系统剪贴板那样优雅,如下所示:

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

答案 1 :(得分:5)

您可以像这样使用机器人类

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)
{

}

答案 2 :(得分:2)

您也可以尝试使用Clipboard类。

答案 3 :(得分:2)

试试这个

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);
}

答案 4 :(得分:1)

答案 5 :(得分:0)

您可以按如下方式使用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();
          }
        }
      }

系统剪贴板中的内容位于结果字符串变量中。 解决方案来自:http://www.javapractices.com/topic/TopicAction.do?Id=82