posted 18 years ago
Painting seems easy at first, and it really is, but there are some seemingly small details that require attention to insure success.
Comments:
In your app you are using getGraphics to access the graphics context of the JFrame for painting. This is not recommended.
Swing decides on its own when to repaint your gui. This can happen at any time and certainly after minimize/restore or re–exposure from beneath other apps.
During each of these episodes your painting code will be properly rendered only if Swing can get to it in this chain of paint calls.
Since getGraphics is only called in your event code it is not rendered during these Swing–initiated repaints.
This is why it is recommended that all painting code be in or originate from the paintComponent method (in Swing).
Trying to paint in the graphics context of a container such as JFrame is not a preferred practice. The paint method in JFrame will paint over everything in the JFrame (see api). Sometimes this is what you need to do but it requires care. The preferred way is to do the painting in a JComponent (JPanels are handy) and add this to your gui container.
The strategy for painting is fairly simple. Put everything in paintComponent that you want to be painted. Let the enclosing class keep state for any variables (like color, size, position) that you want to manipulate and update/display in your painting code. Manipulate these variables from your event code.
Keeping the event–related code separate from the paint–related code will make it easier to understand and write the code that does what you want. This sounds like a cliche but look at the class design/structure in the app below. One class paints graphics. Another class arranges and handles all the user interaction with the app and the subsequent manipulation of variables in the painting class. The challenge with this approach is in deciding how you want the two to communicate with one another.
[ June 26, 2004: Message edited by: Craig Wood ]