- In Swing, painting begins with the
paint
method, 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
repaint
method; do not invoke itspaintComponent
directly. Invokingrepaint
causes the painting subsystem to take the necessary steps to ensure that yourpaintComponent
method is invoked at an appropriate time.
- The multi-arg version of
repaint
allows 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 themoveSquare
method 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
moveSquare
method invokesrepaint
not 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
repaint
multiple 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
Graphics
paramater with the linesuper.paintComponent(g)
as the first line of code in yourpaintComponent
override. 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
RedSquare
class, the application maintains an object-oriented design, which keeps thepaintComponent
method of theMyPanel
class free of clutter. Painting still works because we have passed theGraphics
object 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 overridingpaintSquare
from anywhere higher up in the Swing API.