Often in many of our applications, we need to load and display images. It could be a banner image that you load on top of each window, or the photo of a user that you received over a network which you want to display on a JFrame. A neat solution to this problem can be achieved by drawing the image on a JPanel and placing it among your other GUI components.

In this post I will explain how to create a GUI component which will display an Image object using a JPanel. The following is the code for the JPanel. You can place it among your other GUI components, and when you need to display an image, call the setImage() method with the Image object as the parameter.

package imagepanel;

import java.awt.Graphics;
import java.awt.Image;

/**
 *
 * @author Janith (http://cyberasylum.wordpress.com/)
 */
public class ImagePanel extends javax.swing.JPanel {

    Image image;

    /** Creates new form ImagePanel */
    public ImagePanel() {
        image = null;
        initComponents();
    }

    public void setImage(Image image) {
        this.image = image;
        this.repaint(); //makes a call to the pain() method
    }

    @Override
    public void paint(Graphics g) {
        if (image == null) {
            return;
        }
        g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);  //draw our image over the full area of the JPanel
    }

    private void initComponents() {
        setPreferredSize(new java.awt.Dimension(200, 200));
        setLayout(null);
    }
}

Now you can place this panel in a JFrame, and display images. Assume I have an instance of the above class named as imagePanel, and then I can display the image by:

Image myImage = ImageIO.read(new FileInputStream("test.jpg"));
imagePanel.setImage(myImage);

Click here to download the complete project file of the above code, which also includes a JFrame to test it.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>