JPanel Graphics clearing and repainting?

JDS picture JDS · Aug 1, 2011 · Viewed 56.1k times · Source

I have a JPanel with a paintComponent() function. I'll call it once, then when the user clicks a different JButton, I'll set some flag and want to call this function again as it will do something slightly different after the flag is set.

So here's what I'm wondering: how do I clear the existing stuff from paintComponent? And to redraw, do I just call paintComponent again?

Currently I'm trying the following:

flag2 = true;
repaint(); //I expect (want) paintComponent to be called again

In paint component, I do stuff like:

if (flag2==true) {
    g.drawRect(...);
} else {
    g.drawLine(...);
}

But through testing it seems like there is something wrong with what I'm doing.

Thanks for any help.

Answer

camickr picture camickr · Aug 1, 2011

When you change a property of the panel then you need to invoke:

panel.repaint();

to cause the component to be repainted.

Then the first statement in the paintComponent() method should be:

super.paintComponent(g);

This will paint the background so you can now do your custom painting.

If you need more help then post your SSCCE that demonstrates the problem.