# Java: Who calls paintComponent

When you subclass `JPanel` to draw graphics, override the `paintComponent()` method. It may be called for different reasons.

### Called automatically when it becomes visible

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.

### Called from a user-defined listener via `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.

1. Change instance variables. The listener code should set instance variables that `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()`.
2. Call `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.

## Example

An example of this is in Rolling Dice, where there is a call on `repaint()` whenever the face value instance variable is set.

## References

http://java.sun.com/products/jfc/tsc/articles/painting/index.html
- java.sun.com/products/jfc/tsc/articles/painting/index.html
- java.sun.com/docs/books/tutorial/uiswing/14painting/index.html