Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...