When you subclass JPanel
to
draw graphics, override the paintComponent()
method.
It may be called for different reasons.
When a window becomes visible (uncovered or deminimized) or is resized, the "system"
automatically calls the paintComponent()
method
for all areas of the screen that have to be redrawn.
repaint()
When a listener (mouse, button, keyboard, ...) of yours is called,
the listener code often makse changes that should be
displayed in your graphics area. Never call
paintComponent()
method directly.
paintComponent()
uses in drawing the panel. After changing the values,
the next time paintComponent()
is called,
these new values will be used. But you won't want to wait
for a call to paintComponent()
, call repaint()
.
repaint()
. The repaint()
method consolidates all requests to change the panel
(there may be several repaint requests between screen refreshes).
It adds an update request to the GUI event queue so that the update
will be properly coordinated with other GUI actions (Swing and AWT are not
thread-safe).
This update request, when processed, calls update()
, which
calls paint()
, which calls your paintComponent()
method (as well as calling paintBorder()
and paintChildren()
.
Along the way update()
redrew your background.
An example of this is in Rolling Dice,
where there is a call on repaint()
whenever the face value instance variable is set.