How would I make a paste from java using the system clipboard?

前端 未结 6 1937
我寻月下人不归
我寻月下人不归 2021-01-02 21:35

I want to make a paste from the system clipboard in java. How would I do this?

6条回答
  •  情歌与酒
    2021-01-02 22:11

    You can use the Clipboard class as follows to achieve the paste:

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

    The content from the system clipboard is found in the result string variable. Solution coming from: http://www.javapractices.com/topic/TopicAction.do?Id=82

提交回复
热议问题