Java Data Type How to - Copy String to Clipboard


We would like to know how to copy String to Clipboard.


import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
/*from   www . ja  va 2  s. c  o m*/
public class Main {
  public static void main(String[] args) throws Exception {
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection testData = new StringSelection("Test Data");

    c.setContents(testData, testData);
    // Get clipboard contents, as a String
    Transferable t = c.getContents(null);
    if (t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      Object o = t.getTransferData(DataFlavor.stringFlavor);
      String data = (String) t.getTransferData(DataFlavor.stringFlavor);
      System.out.println("Clipboard contents: " + data);