For several weeks, I have been trying to wrap my brain around the concept of the paint(Graphics g) method. I have a pretty good idea how it works, but I am still struggling with the "practical" application of the paint method with respect to OOP.

I can write small apps using paint(Graphics g) to draw/paint rectangles and lines within a JFrame. And I know that its highly desirable to keep all the "drawing" code INSIDE the paint method. I also understand that paint can be invoked by the system or by the application. Where it starts to get hazy is how, in a "real world" application, I would deal with "incremental painting".

Lets say I am writing an app that draws an ellipse somewhere inside a JFrame right when the JFrame opens, then later on, I want to make that ellipse disappear and a few minutes and several user actions later, I want to draw a rectangle, and so on.

If I have put all my "drawing code" inside the overridden paint method, all the graphics get painted at the same time. This is what is screwing with my head. I can't seem to get to a place in my understanding where I get how to do this incremental painting.

Anyone want to take a shot a helping me over this wall?

Thanks,
Tahoe

Normal method is to use a javax.swing.Timer (not java,util.Timer, which is different) to call back after "a few minutes". In the callback you change the shape etc then call repaint() to trigger Swing to call your paint(...) method.
ps: It's advised to override paintComponent, rather than paint - you can google for the reasons if you're interested.

put all my "drawing code" inside the overridden paint method, all the graphics get painted at the same time

Make each part of the drawing code depend on some controlling variables like a boolean that are set by the Timer or listener code before it calls the repaint method.
The paint method then only does what it has been told to do.

I think I need to go back and review "repaint" and "update".

Now I remember the advantage of "instructor lead" training as opposed to the "self taught" method... The instructor is sort of obligated to hammer on you until you DO understand a concept.

This article has been dead for over six months. Start a new discussion instead.