Image to ClipBoard (linux)
Hi all,
I have problems to place an image on the clipboard (ubuntu 10.10). The
code is below, and for example Gimp says that there is nothing in the
clipboard!
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class testClipboard extends JPanel implements ActionListener{
private Image image;
public testClipboard() {
setPreferredSize(new Dimension(100, 100));
JButton jb = new JButton("Copy");
jb.addActionListener(this);
this.add(jb);
image = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 99, 99);
g.setColor(Color.RED);
g.drawOval(10, 50, 20, 20);
}
@Override
public void actionPerformed(ActionEvent e) {
copyToClipboard();
}
public void copyToClipboard(){
Clipboard clipboard = Toolkit.getDefaultToolkit
().getSystemClipboard();
ImageTransferable selection = new ImageTransferable
(image);
clipboard.setContents(selection, null);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
f.add(new testClipboard
(),BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
});
}
class ImageTransferable implements Transferable{
public ImageTransferable(Image image){
theImage = image;
}
public DataFlavor[] getTransferDataFlavors(){
return new DataFlavor[]
{ DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor){
return flavor.equals(DataFlavor.imageFlavor);
}
public Object getTransferData(DataFlavor flavor) throws
UnsupportedFlavorException{
if (flavor.equals(DataFlavor.imageFlavor)){
return theImage;
}
else{
throw new UnsupportedFlavorException
(flavor);
}
}
private Image theImage;
}
}