How to display a JPanel of JButtons on ImagePanel?

Hi

From the Swing Hacks examples, I can display a JButton on an ImagePanel no problem. But when I put this JButton in JPanel, then add the JPanel to the ImagePanel, the JPanel with the JButton is not displayed.

Can someone please explain why this is?

Here is the ImagePanel code:

import java.awt.*;

import javax.swing.*;

publicclass ImagePanelextends JPanel{

private Image img;

public ImagePanel(String img){

this(new ImageIcon(img).getImage());

}

public ImagePanel(Image img){

this.img = img;

Dimension size =new Dimension(img.getWidth(null),img.getHeight(null));

setPreferredSize(size);

setMinimumSize(size);

setMaximumSize(size);

setSize(size);

setLayout(null);

}

publicvoid paintComponent(Graphics g){

g.drawImage(img,0,0,null);

}

}

And here is the code to add a JButton to a JPanel, then add the JPanel to the ImagePanel:

import javax.swing.*;

import java.awt.event.*;

publicclass ImageTest{

publicstaticvoid main(String[] args){

ImagePanel panel =new ImagePanel(new ImageIcon("images/background.png").getImage());

JPanel buttonPanel =new JPanel()

JButton button =new JButton("Button");

buttonPanel.add(button);

JFrame frame =new JFrame("Hack #XX: Image Components");

frame.getContentPane().add(button);// WORKS!

//frame.getContentPane().add(buttonPanel);// NO BUTTON IS DISPLAYED?

frame.pack();

frame.setVisible(true);

}

}

Thanks

[3042 byte] By [fdgfda] at [2007-11-27 10:13:55]
# 1

> setLayout(null);

When you use a null layout then you are responsible for setting the size and location of any component added to the panel. The default location is (0,0) so thats ok, but the default size of the button panel is also (0,0) which is why nothing get painted.

Don't use a null layout. Let the layout manager layout any component added to it.

Also, I would override the getPreferredSize() method of your ImagePanel to return the size of the image, instead of setting the preferred size in the constructor.

camickra at 2007-7-28 15:30:01 > top of Java-index,Desktop,Core GUI APIs...
# 2

Thankyou, you're answer is much appreciated.

fdgfda at 2007-7-28 15:30:01 > top of Java-index,Desktop,Core GUI APIs...