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

Viewed 17541

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

6 Answers

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

Related