Java clipboard: How to place text on the clipboard

Here’s a “Java clipboard” method I use when writing a Java/Swing program that needs to place plain text (a String) on the system clipboard:

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

This Java clipboard method takes a String as an argument, then places that string on the clipboard for you, making this clipboard text available to other applications. If you have something you want to be a ClipboardOwner you can pass that in as an argument, but I often just pass a null argument to the method, like this:

writeToClipboard(msg, null);

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

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