//Calling function
ImagePanel Panel_2 = new ImagePanel(new ImageIcon("C:/Users/kagarwal/Downloads/intacct_logo_standard_web.png").getImage());
Panel_2.add(new JButton());
Panel_2.revalidate();
//Called function
public class ImagePanel extends 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);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
要求是:JPanel2需要有一个背景图片,最重要的是我们需要添加JButton。但是,这里的问题是新添加的JButton没有出现在给定的JPanel中,它只显示背景图像。我错过了刷新吗?
答案 0 :(得分:4)
问题出在paintComponent中,你只要求图形对象绘制图像。 但是你应该通过调用传递图形对象的super.paintComponent()调用超类paintComponent方法,以便正确显示面板的所有组件。