Copying text to the clipboard using Java

user765134 picture user765134 · Jul 15, 2011 · Viewed 112k times · Source

I want to copy text from a JTable's cell to the clipboard, making it available to be pasted into other programs such as Microsoft Word. I have the text from the JTable, but I am unsure how to copy it to the clipboard.

Answer

LouwHopley picture LouwHopley · Jul 15, 2011

This works for me and is quite simple:

Import these:

import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;

And then put this snippet of code wherever you'd like to alter the clipboard:

String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);