Getting and Setting an Image on the System Clipboard - Java Native OS

Java examples for Native OS:Clipboard

Description

Getting and Setting an Image on the System Clipboard

Demo Code


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

public class Main {
  public static Image getClipboard() {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard()
        .getContents(null);//w w w . jav  a2  s .  co m

    try {
      if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
        Image text = (Image) t.getTransferData(DataFlavor.imageFlavor);
        return text;
      }
    } catch (UnsupportedFlavorException e) {
    } catch (IOException e) {
    }
    return null;
  }

  public static void setClipboard(Image image) {
    ImageSelection imgSel = new ImageSelection(image);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
  }   
}

class ImageSelection implements Transferable {
  private Image image;

  public ImageSelection(Image image) {
    this.image = image;
  }

  // Returns supported flavors
  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { DataFlavor.imageFlavor };
  }

  // Returns true if flavor is supported
  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return DataFlavor.imageFlavor.equals(flavor);
  }

  // Returns image
  public Object getTransferData(DataFlavor flavor)
      throws UnsupportedFlavorException, IOException {
    if (!DataFlavor.imageFlavor.equals(flavor)) {
      throw new UnsupportedFlavorException(flavor);
    }
    return image;
  }
}

Related Tutorials