Reputation: 139
Kind of an odd problem.
I have an ArrayList of "Circles" that I'm having be drawn in my drawing panel but before they are drawn they are validated by a method which checks if they are within the panel, meaning 100 within confines of panel. The amount of Circles that pass this "drawn()" method are counted by my circlesDrawn integer variable and then printed in the console later in the method.
I am printing the data here in the paintComponent method for the sake of it syncing properly as I was having issues doing so within my driver main method. However, when my program runs this data is printed three times over, the second and third times the circlesDrawn variable is twice and three times in value respectively.
Is there any way to prevent this from occurring or any useful pointers anyone can give me how to rectify this?
I've only attached the paintComponent method to avoid dumping my entire project out here but if more context is needed I can easily supply it.
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i = 0; i < circles.size(); ++i)
{
if (circles.get(i).drawn(DEFAULT_WIDTH, DEFAULT_HEIGHT) == true)
{
circles.get(i).draw(g);
circlesDrawn++;
}
}
System.out.println("Number of circles drawn: " + circlesDrawn);
}
Thanks in advance for the help.
Upvotes: 0
Views: 238
Reputation: 285405
Is there a way of preventing this from happening?
No, and moreover you don't want to try to do this. Realize that you don't have full control over when or even if painting methods are called -- for instance if repaint requests are stacked, likely not all be called, and also the JVM will sometimes initiate painting at the OS's request, regardless of your code. So for this reason you should make sure that your code doesn't depend on having this control. About the best you can do is to limit the area of repainting when doing a repaint(...)
call, by passing in an appropriate parameter.
For more, please see, Painting in AWT and Swing
Note that this portion of your question confuses me:
I am printing the data here in the paintComponent method for the sake of it syncing properly as I was having issues doing so within my driver main method.
Can you elaborate a bit more on this? This shouldn't be an issue if your code follows Swing threading rules.
Upvotes: 5