General Comments and Recommendations
- One way: Draw in a BufferedImage getting your Graphics object from the BufferedImage, and then draw the BufferedImage in the JComponent's (JPanel's?) paintComponent method.
- If you do it this way, you will use the Graphics object directly obtained from the BufferedImage to do your drawing.
- Don't forget to dispose of this Graphics object when done with it.
- The actual drawing though is done in the JPanel's
paintComponent(...)
method (see below). - Another way: change a class field, and have the JPanel's paintComponent method use that field when painting. For instance, if you want to paint multiple Rectangles, create an
ArrayList<Rectangle>
add to it in your ActionListener, callrepaint()
and have thepaintComponent(...)
method iterate through the List, drawing rectangles held by it. - Note that the
paintComponent(...)
method is never called directly but rather you suggest to the JVM that it call it by callingrepaint()
. - Never dispose of a Graphics object that was given to you by the JVM, for instance the one passed into the
paintComponent(Graphics g)
parameter.
Links
- Basic Tutorial: Lesson: Performing Custom Painting
- More advanced concepts: Painting in AWT and Swing