A Java method to copy text to the operating system clipboard

Here’s some source code for a Java method that lets you copy text (a String) to the clipboard on your operating system:

public void writeToClipboard(String s, ClipboardOwner owner) {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable transferable = new StringSelection(s);
    clipboard.setContents(transferable, owner);
}

Don’t worry about that ClipboardOwner reference too much; you can just set it to null when calling this method, like this:

writeToClipboard(textArea.getText(), null);

If you wanted to see how to write a string to the clipboard in Java, I hope this example and source code is helpful.

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

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