The_Lost_Avatar
The_Lost_Avatar

Reputation: 990

Extended class of JPanel not showing properties of JPanel

I am using a class RefreshablePanel that extends JPanel

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

Now when I do it like this

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

enter image description here

Upvotes: 0

Views: 84

Answers (2)

tbodt
tbodt

Reputation: 16997

The reason this has changed is because when you override paintComponent, you must always call super.paintComponent(g) as the first line:

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

The paintComponent method in the JPanel superclass paints the background, so if you insert super.paintComponent(g), the background will be painted before you paint anything custom.

Upvotes: 3

camickr
camickr

Reputation: 324137

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

You should always invoke super.paintComponent() when you override the paintComponent() method.

Upvotes: 3

Related Questions