JPanel Graphics clearing and repainting?

你。 提交于 2019-12-18 04:16:06

问题


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.


回答1:


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.




回答2:


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




回答3:


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?




回答4:


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.



来源:https://stackoverflow.com/questions/6902771/jpanel-graphics-clearing-and-repainting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!