Set an image on the clipboard with a custom Transferable object to hold the image in Java

Description

The following code shows how to set an image on the clipboard with a custom Transferable object to hold the image.

Example


//from   w w  w.  j  av  a 2  s  .  co m
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;

import javax.swing.ImageIcon;

public class Main {
  public static void main(String[] argv) throws Exception {

    ImageSelection imgSel = new ImageSelection(new ImageIcon("a.png").getImage());
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
  }
}

class ImageSelection implements Transferable {
  private Image image;

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

  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { DataFlavor.imageFlavor };
  }

  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return DataFlavor.imageFlavor.equals(flavor);
  }

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

The code above generates the following result.





















Home »
  Java Tutorial »
    Development »




Java Algorithms
Java Clipboard
Java Compiler
Java Desktop
Java Virtual Machine
Java Math
OS
Random
Java Robot
Java RuntimeMXBean
Java Timer
Java UUID
Java Internationalization