Java Swing Tutorial - Java Clipboard.getData(DataFlavor flavor)


Clipboard.getData(DataFlavor flavor) has the following syntax.

public Object getData(DataFlavor flavor)  throws UnsupportedFlavorException ,   IOException


In the following code shows how to use Clipboard.getData(DataFlavor flavor) method.

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
/*from   ww  w  .  ja  v  a 2  s . c  o m*/
public class Main implements ClipboardOwner {
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

  public Main() {
    // Implement Copy operation
    StringSelection contents = new StringSelection("data");
    clipboard.setContents(contents, this);

    // Implement Paste operation
    Transferable content = clipboard.getContents(this);
    String dstData;
    try {
      dstData = (String) content.getTransferData(DataFlavor.stringFlavor);
    } catch (Exception e) {

  public void lostOwnership(Clipboard clipboard, Transferable contents) {
    System.out.println("Clipboard contents replaced");

  public static void main(String[] args) {
    Main test = new Main();

The code above generates the following result.