9

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
JDS
  • 16,388
  • 47
  • 161
  • 224
  • You're not calling repaint() from within the paintComponent method, are you? Are you sure the repaint() call is associated with the panel you want refreshed? (e.g. myPanel.repaint())? – Amir Afghani Aug 01 '11 at 18:41

4 Answers4

15

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
14

To clear all previously drawn graphics, invoke g.clearRect(0, 0, getWidth(), getHeight()).

mre
  • 43,520
  • 33
  • 120
  • 170
2

First, why not use an enum instead of a boolean?

enum Enum { 
    RECTANGLE,
    LINE,
    CIRCLE
}

Enum choice = RECTANGLE; //default to RECTANGLE

switch(choice) { 
   // case RECTANGLE, LINE, CIRCLE
}

With regards to your issue, can you answer my comments in your question?

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
  • The logic I have is fine, I could probably use enum but whatever that's not my problem. My problem is that I need to clear all drawn graphics and then call paintComponent again somehow for this JPanel. – JDS Aug 01 '11 at 18:55
  • You shouldn't need to clear all the graphics to achieve what you want. – Amir Afghani Aug 01 '11 at 19:32
  • See camickr's answer, if you aren't doing what he's outlined, focus on that first. – Amir Afghani Aug 01 '11 at 19:33
2

I would suggest calling revalidate(); instead of repaint(). revalidate() needs to be called when changing the size / layout or when you add/remove objects onto your jpanel and will update all of it's children. From what I can tell, you're still using the same paint object tho but changing it's layout.

John Snow
  • 5,214
  • 4
  • 37
  • 44