Either 1) draw in a BufferedImage which is then displayed inside of your paintComponent
override, or 2) put your data into an ArrayList or other collection, and then iterate through the collection inside of paintComponent
. I'd do the latter if I needed the data for other purposes. Also, never ever do this:
public void update(Graphics g) {
paintComponent(g);
}
This is not how Swing graphics are supposed to be done and is potentially dangerous code. Please read:
Edit
More detail regarding option 1:
- Create a BufferedImage using one of its constructors.
- Do your drawing on the image.
- When you need to draw, get a Graphics object from the BufferedImage using
getGraphics()
orcreateGrahpics()
(for a Graphics2D object) - Draw with this Graphics object
- Then
dispose()
the Graphics object.
- When you need to draw, get a Graphics object from the BufferedImage using
- Then call
repaint()
to ask the JVM to repaint the component. - Draw the image in your
paintComponent
method by callingg.drawImage(...)
, passing in your buffered image.
Benefits: often the drawing is quicker, and I often use this to draw background images.
Drawbacks: the data points are not available, and so if you need to do manipulation or animation of your data points, this is not the way to go.