Home Java Java-tips GUI-lowlevel Graphics Who calls paintComponent

Ask Questions?

View Latest Questions

Advertisement


 
 

Who calls paintComponent
Posted on: July 26, 2006 at 12:00 AM
you subclass JPanel to draw graphics, override the paintComponent() method.

Java Notes

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 indirectly 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

Copyleft 2004 Fred Swartz MIT License
Advertisement


DMCA.com