2016-07-28 90 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方法,以便正確顯示面板的所有組件。