To display an image in a panel, override the paintComponent(Graphics)
method and draw it there:
public class ImagePanel extends JPanel {
private Image image;
public void setImage (Image image) {
this.image = image;
revalidate();
repaint();
}
@Override
protected void paintComponent (Graphics g) {
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0, 0, this);
}
}
you also should override the getPreferredSize() method to expose how large your image component should be (will be used by the layout manager of the parent container):
@Override
public Dimension getPreferredSize () {
if (image == null) {
return super.getPreferredSize();
}
Insets insets = getInsets();
return new Dimension(image.getWidth(this) + insets.left + insets.right, image.getHeight(this) + insets.top + insets.bottom);
}
Edit: JLabel
(as pointed out by the other answers) is fine for displaying simple images or icons, but when you need advanced features such as automatic up-/downscaling (with or without keeping proportions), tiling (x, y, both), it's usually better to create a specialized image panel class for that.