Having images as background of JPanel

Why not make a single class that takes a Image??

public class ImagePane extends JPanel {

    private Image image;

    public ImagePane(Image image) {
        this.image = image;
    }

    @Override
    public Dimension getPreferredSize() {
        return image == null ? new Dimension(0, 0) : new Dimension(image.getWidth(this), image.getHeight(this));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.drawImage(image, 0, 0, this);
        g2d.dispose();
    }
}

You would even provide hints about where it should be painted.

This way, you could simply create an instance when ever you needed it

Updated

The other question is, why?

You could just use a JLabel which will paint the icon for you without any additional work…

See How to use labels for more details…

This is actually a bad idea, as JLabel does NOT use it’s child components when calculating it’s preferred size, it only uses the size of the image and the text properties when determining it’s preferred size, this can result in the component been sized incorrectly

Leave a Comment

tech