Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background image in a JFrame

This question has been asked a lot but everywhere the answers fall short. I can get a JFrame to display a background image just fine by extending JPanel and overriding paintComponent, like so:

class BackgroundPanel extends JPanel {
    private ImageIcon imageIcon;
    public BackgroundPanel() {
        this.imageIcon = Icons.getIcon("foo");
  }

    @Override
    protected void paintComponent(Graphics g) {
       super.paintComponent(g);
        g.drawImage(imageIcon.getImage(), 0,0,imageIcon.getIconWidth(),imageIcon.getIconHeight(),this);
    }
}

But now, how do you add a component on top of that background? When I go

JFrame w = new JFrame() ;
Container cp = w.getContentPane();
cp.setLayout(null);

BackgroundPanel bg = new BackgroundPanel();
cp.add(bg);

JPanel b = new JPanel();
b.setSize(new Dimension(30, 40));
b.setBackground(Color.red);
cp.add(b);
w.pack()
w.setVisible(true)

It shows the little red square (or any other component) and not the background, but when I remove cp.setLayout(null);, the background shows up but not my other component. I'm guessing this has something to do with the paintComponent not being called by the null LayoutManager, but I'm not at all familiar with how LayoutManagers work (this is a project for college and the assignment specifically says not to use a LayoutManager).

When i make the image the background has to display null (and so, transparant (??)) the red square shows up so it might be that the background is actually above my other components.

Does anyone anyone have any ideas?

Thanks

like image 740
thepandaatemyface Avatar asked Mar 14 '26 08:03

thepandaatemyface


1 Answers

When using null layout (and you almost never should) you have to supply a bounds for every component, otherwise it defaults to (0 x,0 y,0 width,0 height) and the component won't display.

BackgroundPanel bg = new BackgroundPanel();
cp.add(bg);

isn't supplying a bounds. You'll need to do something like:

BackgroundPanel bg = new BackgroundPanel();
bg.setBounds(100, 100, 100, 100);
cp.add(bg);

Which would make bg size 100 x 100 and place it at 100 x, 100 y on the frame.

like image 127
Nate Avatar answered Mar 16 '26 20:03

Nate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!