I have a program that creates random generate shapes on a canvas when the mouse is clicked. I then change the color of the shape if it already exists on the canvas. Right now, my code changes the shape to red and creates a new random shape. How can I get it to just color the shape without creating a new random shape. I tried adding the shapes to the arraylist and repaint right after coloring the shape but I get compile errors. Any nudge in the right direction would be appreciated. Thanks
Looks okay to me. (Except for the title: you certainly wouldn't use a MouseListener to paint on a canvas.)
But you say you get compile errors? Then you should read them and fix your code accordingly. Of course you could TellTheDetails here if you were having problems understanding them.
Joined: Jun 30, 2011
I get the compile Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException when i try and add the shape back to the arraylist and repaint if it finds the shapes that was clicked.
My goal is to have it find a shape on the canvas and paint it a different color. Right now, it changes the color of the shape it finds and creates a new shape in the same mouse click location.
You're iteration through a List. During that iteration you're trying to add an element to that List. That is not allowed resulting in the exception you're getting. You probably want to rethink your algorithm.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
This may sound very simplistic but have you tried an if/else condition? It could work if a new Shape, with matching values to an existing Shape, is considered equal to the other Shape. It all comes down to both the equals() method of your Shape objects and how your List evaluates its contains() method.
Aside, Is there something about switch that turns people away from using both if/else and switch in the same place? Like a mental block (I think I might also have this )?
Also, I really shouldn't encorage you to hog the Event dispatching Thread, with these things, by running several possibly long-running computations, which will freeze other Event calls until it returns. Perhaps you could call a method on an existing class, or use a Runnable, Thread, start()?
Finally a mention, because you reported a ConcurrentModificationException, that ArrayList isn't synchronized : Read the Java SE API's java.util.ArrayList class description -- "Note that this implementation is not synchronized.", and this could cause problems with special methods like paint().