2016-07-28 93 views
0
//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中,它只显示背景图像。我是否缺少刷新?如何向JPanel添加背景,然后在该JPanel上添加一个JButton

回答

4

问题出在paintComponent中,你只要求图形对象绘制图像。 但是,您应通过调用super.paintComponent()传递图形对象来调用超类paintComponent方法,以便正确显示面板的所有组件。