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
source share