Copying to the clipboard in Java

clone1018 picture clone1018 · Aug 28, 2010 · Viewed 78.6k times · Source

I want to set the user's clipboard to a string in a Java console application. Any ideas?

Answer

user85421 picture user85421 · Aug 28, 2010

Use the Toolkit to get the system clipboard. Create a StringSelection with the String and add it to the Clipboard.

Simplified:

StringSelection selection = new StringSelection(theString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);