JFrame Background Image

This question is asked very often, but everywhere the answers do not match. I can get a JFrame to render the background image just fine, extending the JPanel and overriding the paintComponent, for example:

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 this 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 a small red square (or any other component), not the background, but when I cp.setLayout(null); A background appears, but not my other component. I suppose this has something to do with the fact that paintComponent is not called by the null LayoutManager, but I am not at all familiar with how the LayoutManagers work (this is a college project, and the assignment specifically says not to use LayoutManager).

When I make an image, the background should display zero (which means transparent (??)) a red square appears, so it may be that the background is really higher than my other components.

Does anyone have any ideas?

thanks

+3
source share
3 answers

When using a null layout (and you almost never have to) you must provide ratings for each component, otherwise it defaults to (0 x, 0 y, 0 width, 0 height) and the component will not be displayed.

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

does not provide boundaries. You will need to do something like:

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

To make bg 100 x 100 and place it at 100 x, 100 y per frame.

+5
source

See the Root Pane documentation for all the information you need. Pay attention to the availability of laminated panels and glass, as well as content panels.

+3
source

By default, all components have a size of 0. Just because you are painting on a component does not give the component a size. You are still responsible for sizing. This is why you should always use the layout manager. He takes care of all things of this size for you, so you do not need to worry.

I do not know why beginners always think that they cannot use the layout manager. Yes, it takes a few more minutes to learn, but in the long run it will save you a lot of grief.

The background panel shows several approaches. Again, both of them assume that you are using the layout manager, so you may need to set the size manually.

+2
source

Source: https://habr.com/ru/post/1311656/


All Articles