0

我正在使用一个扩展 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);

在此处输入图像描述

现在当我这样做时

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

在此处输入图像描述

4

2 回答 2

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

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

于 2013-10-02T19:14:07.297 回答
3

之所以更改,是因为当您覆盖时paintComponent,您必须始终将super.paintComponent(g)其作为第一行调用:

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

超类中的paintComponent方法JPanel绘制背景,所以如果你 insert super.paintComponent(g),背景将在你绘制任何自定义之前绘制。

于 2013-10-02T19:15:12.360 回答