扩展的JPanel类没有显示JPanel的属性

时间:2013-10-02 19:10:41

标签: java swing inheritance panel

我正在使用扩展JPanel的类RefreshablePanel

public class RefreshablePanel extends JPanel {
    static String description="";
    protected void paintComponent(Graphics g){
        g.drawString(description, 10, 11);
}
    void updateDescription(String dataToAppend){    
        description = description.concat("\n").concat(dataToAppend);
       }    
}

JPanel descriptionPanel = new JPanel();
scrollPane_2.setViewportView(descriptionPanel);
descriptionPanel.setBackground(Color.WHITE);
descriptionPanel.setLayout(null);

enter image description here

现在当我这样做时

RefreshablePanel descriptionPanel = new RefreshablePanel();
scrollPane_2.setViewportView(descriptionPanel);
descriptionPanel.setBackground(Color.WHITE);
descriptionPanel.setLayout(null); 

enter image description here

2 个答案:

答案 0 :(得分:3)

protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawString(description, 10, 11);
}

覆盖paintComponent()方法时,应始终调用super.paintComponent()。

答案 1 :(得分:3)

这种情况发生变化的原因是,当您覆盖paintComponent时,您必须始终将super.paintComponent(g)作为第一行:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString(description, 10, 11);
}

paintComponent超类中的JPanel方法绘制背景,因此如果插入super.paintComponent(g),则在绘制任何自定义内容之前将绘制背景。