7.13.2. Transferring Text

The best way to get comfortable with the data transfer classes is to start with the simplest situation: transferring text to and from the system clipboard. First, get a reference to the system clipboard:

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

For strings to be transferred to the clipboard, they must be wrapped into StringSelection objects.

String text = . . . StringSelection selection = new StringSelection(text);

The actual transfer is done by a call to setContents, which takes a StringSelection object and a ClipBoardOwner as parameters. If you are not interested in designating a clipboard owner, set the second parameter to null.

clipboard.setContents(selection, ...

Get Core Java® Volume II—Advanced Features, Ninth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.