The following illustrates pasting an image from clipboard in Java and setting it as background image for JFrame.
// Import for BorderLayout
import java.awt.*;
// Import for JFrame, JLabel
import javax.swing.*;
// Import for Clipboard, DataFlavor
import java.awt.datatransfer.*;
// Import for BufferedImage
import java.awt.image.*;
class PasteImage extends JFrame
{
JLabel l;
public PasteImage()
{
// Set frame properties
setTitle("Paste Image");
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
// UnsupportedFlavorException, IOException can be raised.
try
{
// Get image type data from the clipboard (Object type is returned) but type casted to BufferedImage
l=new JLabel(new ImageIcon((BufferedImage)Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.imageFlavor)));
}catch(Exception e){
// If image is not found, try text!
try
{
// Create a JLabel containing text that is in the clipboard
l=new JLabel((String)Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor));
}catch(Exception e1){
// If nothing was there in the clipboard..
l=new JLabel("Nothing is there in the clipboard!");
}
}
// Add the JLabel to the frame
add(l);
// Pack it tightly!
pack();
// Center the JFrame
setLocationRelativeTo(null);
}
public static void main(String args[])
{
new PasteImage();
}
}
Toolkit.getDefaultToolkit().getSystemClipboard(): Toolkit class has a public static method getDefaultToolkit() which returns an instance of the java.awt.Toolkit class which is useful for calling the normal public method getSystemClipboard(). This method returns the java.awt.datatransfer.Clipboard object which will further be used to get data from the system clipboard.
getData(DataFlavor.imageFlavor): Get the data in the clipboard that is in the form of an image. Here is how to get text from clipboard in Java
Note: To make this kegiatan successful and see an image, before executing the kegiatan don't forget to copy any image to the clipboard.
Also see my post on AWT Tutorial in Java
Also see my post on AWT Tutorial in Java
Paste image from Clipboard in Java |