- In Swing, painting begins with the
paintmethod, which then invokespaintComponent,paintBorder, andpaintChildren. The system will invoke this automatically when a component is first painted, is resized, or becomes exposed after being hidden by another window.
- Programatic repaints are accomplished by invoking a component's
repaintmethod; do not invoke itspaintComponentdirectly. Invokingrepaintcauses the painting subsystem to take the necessary steps to ensure that yourpaintComponentmethod is invoked at an appropriate time.
- The multi-arg version of
repaintallows you to shrink the component's clip rectangle (the section of the screen that is affected by painting operations) so that painting can become more efficient. We utilized this technique in themoveSquaremethod to avoid repainting sections of the screen that have not changed. There is also a no-arg version of this method that will repaint the component's entire surface area.
- Because we have shrunk the clip rectangle, our
moveSquaremethod invokesrepaintnot once, but twice. The first invocation repaints the area of the component where the square previously was (the inherited behavior is to fill the area with the current background color.) The second invocation paints the area of the component where the square currently is.
- You can invoke
repaintmultiple times from within the same event handler, but Swing will take that information and repaint the component in just one operation.
- For components with a UI Delegate, you should pass the
Graphicsparamater with the linesuper.paintComponent(g)as the first line of code in yourpaintComponentoverride. If you do not, then your component will be responsible for manually painting its background. You can experiment with this by commenting out that line and recompiling to see that the background is no longer painted.
- By factoring out our new code into a separate
RedSquareclass, the application maintains an object-oriented design, which keeps thepaintComponentmethod of theMyPanelclass free of clutter. Painting still works because we have passed theGraphicsobject off to the red square by invoking itspaintSquare(Graphics g)method. Keep in mind that the name of this method is one that we have created from scratch; we are not overridingpaintSquarefrom anywhere higher up in the Swing API.