Explore Java

Be Social. Be Updated.

  • Stumble
  •   
  •   

Paste Image from Clipboard on JFrame in Java



An example on pasting an image that is on system clipboard in Java on a JFrame. Here we've used a JLabel and set the image from the clipboard to it as icon.


Example



// 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();

}

}

Explanation


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.

Note: To make this program successful and see an image, before executing the program don't forget to copy any image to the clipboard.

Output


Paste image from Clipboard in Java.
Paste image from Clipboard in Java

Also see my other post on Getting data from Clipboard in Java

0 comments:

About This Blog

This blog contains Java Tutorials, Code Samples,demonstrating several concepts in Java. All the code samples are well tested by a team of experts and hence there will be no programmatical errors. We are seamlessly thriving in making the tutorials easier for beginners.

About the Author

was a software and technology enthusiast. He is a 12th grade student and a part time blogger with extreme love in Java programming.Follow him on Google+ and Twitter or befriend him on Facebook and also on