The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
By now you know that the paintComponent
method is where all of your painting code should be placed. It is true that this method will be invoked when it is time to paint, but painting actually begins higher up the class hierarchy, with the paint
method (defined by java.awt.Component
.) This method will be executed by the painting subsystem whenever you component needs to be rendered. Its signature is:
public void paint(Graphics g)
javax.swing.JComponent
extends this class and further factors the paint
method into three separate methods, which are invoked in the following order:
protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)
The API does nothing to prevent your code from overriding paintBorder
and paintChildren
, but generally speaking, there is no reason for you to do so. For all practical purposes paintComponent
will be the only method that you will ever need to override.
As previously mentioned, most of the standard Swing components have their look and feel implemented by separate UI Delegates. This means that most (or all) of the painting for the standard Swing components proceeds as follows.
paint()
invokes paintComponent()
.ui
property is non-null, paintComponent()
invokes ui.update()
.opaque
property is true, ui.update()
fills the component's background with the background color and invokes ui.paint()
.ui.paint()
renders the content of the component.This is why our SwingPaintDemo
code invokes super.paintComponent(g)
. We could add an additional comment to make this more clear:
public void paintComponent(Graphics g) { // Let UI Delegate paint first, which // includes background filling since // this component is opaque. super.paintComponent(g); g.drawString("This is my custom Panel!",10,20); redSquare.paintSquare(g); }
If you have understood all of the demo code provided in this lesson, congratulations! You have enough practical knowledge to write efficient painting code in your own applications. If however you want a closer look "under the hood", please refer to the SDN article linked to from the first page of this lesson.