Java clipboard example: How to write text to the system clipboard

I was just digging around through one of my Java Swing applications, and I found this method that writes a given String to the system clipboard, using the Toolkit, Clipboard, and Transferable classes, and I thought I’d share it here.

Here’s the Java source code for this method that I named writeTextToClipboard:

public static void writeTextToClipboard(String s) {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable transferable = new StringSelection(s);
    clipboard.setContents(transferable, null);
}

As you can see, there isn’t too much to this code. The only thing I’ll say about it is that I limited it to work with Strings, but there’s no reason you have to do this in other applications. I just knew that I was only going to be working with text, so I made that assumption here.

Using the Scala syntax, these are the import statements you’ll need:

import java.awt.Toolkit
import java.awt.datatransfer.{Clipboard, StringSelection, Transferable}