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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.