Java Swing Tutorial - Java Transferable .isDataFlavorSupported (DataFlavor flavor)








Syntax

Transferable.isDataFlavorSupported(DataFlavor flavor) has the following syntax.

boolean isDataFlavorSupported(DataFlavor flavor)

Example

In the following code shows how to use Transferable.isDataFlavorSupported(DataFlavor flavor) method.

//from  w ww .j  a  v a2  s . c o m

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
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 void main(String args[]) {
    String toClipboard = "Hello from Java!";
    StringSelection ss = new StringSelection(toClipboard);
    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    clip.setContents(ss, ss);
    clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable contents = clip.getContents(new Main().getClass());
    if (contents == null) {
      System.out.println("The clipboard is empty.");
      return;
    }
    if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      try {
        String data = (String) contents.getTransferData(DataFlavor.stringFlavor);
        System.out.println(data);
      } catch (IOException ex) {
        System.out.println("IOException");
      } catch (UnsupportedFlavorException ex) {
        System.out.println("UnsupportedFlavorException");
      }
    } else{
      System.out.println("Wrong flavor.");
    }
  }
}

The code above generates the following result.