2

I have a JPanel (which I created using netbeans)and I need to load image in it, based on selection on previous page. Could anyone suggest how to do that. Also is JPanel the best way to do what I am trying to do, or I could do something else ?

Efforts appreciated thanks!!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
koool
  • 15,157
  • 11
  • 45
  • 60
  • On the top right of every stackoverflow page is a textbox where a grey prompt states: '**search**'. This means you could click in this box and enter some words (like '`image jpanel`') and press the return key. The webpage _magically_ reloads and shows you a list of questions (and answers!) containing these words. I took care of this for you and I'm proud to present you the second hit: http://stackoverflow.com/questions/1242581/display-a-jpg-image-on-a-jpanel ;-) – bobndrew Oct 10 '11 at 08:42

3 Answers3

3

There are number of ways to read/load images in Java. Take a look at this tutorial.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • Hey ! thanks for that ... but I am using JPanel and I have already initialized my panel using drag and drop in Netbeans ... I now have to figure out how to load that with Image ... Thanks for the effort though +1 – koool Oct 10 '11 at 06:33
3

The easiest way to display an image is to use a JLabel and call its setIcon method (or its constructor). The icon can be loaded using one of the constructors of the ImageIcon class.

See http://download.oracle.com/javase/tutorial/uiswing/components/label.html for an example.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

This is a sample code demonstrating how to load image in JPanel; background.jpg is the image we are loading to the JPanel. Also note that this image should be available in the source.

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageTest {

    public static void main(String[] args) {
        ImagePanel panel = new ImagePanel(
            new ImageIcon("background.jpg").getImage());

        JFrame frame = new JFrame();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

class ImagePanel extends JPanel {

    private Image img;

    public ImagePanel(String img) {
        this(new ImageIcon(img).getImage());
    }

    public ImagePanel(Image img) {
        this.img = img;
        Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        setSize(size);
        setLayout(null);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}
Catalina Island
  • 7,027
  • 2
  • 23
  • 42
COD3BOY
  • 11,964
  • 1
  • 38
  • 56