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

