Painting is destructive, that is, each time paint
is called, it will clear/remove what ever was painted before it.
This is very important, as the Graphics
context is shared by all the components that are painted during the paint cycle, meaning, when it gets to you, it might already have something painted on it.
You need to do two things.
First, you need to create something that is paintable, that is, some kind of object which provides a simple paint
or draw
method which you can pass the Graphics
context to. This object should know what it's painting and in what color
Second, you need to add each of these "paintable" objects to a List
of some kind as they are created. This will allow you to loop through the List
and repaint them when you need to.
You should avoid overriding paint
of top level containers like JFrame
, apart from the fact that they aren't double buffered and can produce flickering when updated, you could end up painting under the borders of the frame's decorations (0x0 is actually the top left of the window/frame, not the viewable area under the frame's title bar).
Instead, use a JPanel
and override it's paintComponent
method
Take a look at Performing Custom Painting and Painting in AWT and Swing for more details
Updated...
You color list is out of sync with your mouse points because you did...
colors.add(Color.black);
In the constructor. This means that the first circle will be painted in black and the next in the selected color. When you change colors, it is still out of sync