Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
paint
method, which then invokes paintComponent
, paintBorder
, and paintChildren
. The system will invoke this automatically when a component is first painted, is resized, or becomes exposed after being hidden by another window.repaint
method; do not invoke its paintComponent
directly. Invoking repaint
causes the painting subsystem to take the necessary steps to ensure that your paintComponent
method is invoked at an appropriate time.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 the moveSquare
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.moveSquare
method invokes repaint
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.repaint
multiple times from within the same event handler, but Swing will take that information and repaint the component in just one operation.Graphics
paramater with the line super.paintComponent(g)
as the first line of code in your paintComponent
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.RedSquare
class, the application maintains an object-oriented design, which keeps the paintComponent
method of the MyPanel
class free of clutter. Painting still works because we have passed the Graphics
object 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 paintSquare
from anywhere higher up in the Swing API.