In Swing, painting begins with the
paintmethod, which then invokes
paintChildren. 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 its
repaintcauses the painting subsystem to take the necessary steps to ensure that your
paintComponentmethod 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 the
moveSquaremethod 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
repaintnot 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 line
super.paintComponent(g)as the first line of code in your
paintComponentoverride. 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 the
paintComponentmethod of the
MyPanelclass free of clutter. Painting still works because we have passed the
Graphicsobject off to the red square by invoking its
paintSquare(Graphics g)method. Keep in mind that the name of this method is one that we have created from scratch; we are not overriding
paintSquarefrom anywhere higher up in the Swing API.