Getting and Setting Text on the System Clipboard - Java Native OS

Java examples for Native OS:Clipboard

Description

Getting and Setting Text on the System Clipboard

Demo Code

import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class Main {
  public static String getClipboard() {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
        .getContents(null);/* w  w  w. ja  va2  s . c  om*/

    try {
      if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        String text = (String) t.getTransferData(DataFlavor.stringFlavor);
        return text;
      }
    } catch (UnsupportedFlavorException e) {
    } catch (IOException e) {
    }
    return null;
  }
  public static void setClipboard(String str) {
    StringSelection ss = new StringSelection(str);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
  }
}

Related Tutorials