# Java Notes

# Who calls paintComponent

When you subclass `JComponent` or `JPanel` to draw graphics, override the `paintComponent()` method. This method is called because the user did something with the user interface that required redrawing, or your code has explicitly requested that it be redrawn.

### 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 indirectly from a user-defined listener via `repaint()`

When a listener (mouse, button, keyboard, ...) of yours is called, the listener code often makes 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 component (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()`.

## Example

An example of this is in Roll 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
- java.sun.com/docs/books/tutorial/uiswing/14painting/concepts.html