Java Example Program / Sample Source 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.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class TransferableExample{
public static void main(String[] argv) throws Exception {
// setting image to Clipboard
Image image = ImageIO.read(new File("C:\\bw-javaprog-year.png"));
ImageSelection imgSelection = new ImageSelection(image);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSelection, null);
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
try {
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
// getting image from Clipboard
image = (Image) transferable.getTransferData(DataFlavor.imageFlavor);
System.out.println(image);
}
} catch (UnsupportedFlavorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ImageSelection implements Transferable {
private Image image;
public ImageSelection(Image image) {
this.image = image;
}
// Need to override following 3 methods;
// 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;
}
}
adsense4 |
|
|