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

最佳答案

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

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


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

10-04 19:21