关于java:Swing中paint,paintComponent和paintComponents之间的区别

Difference between paint, paintComponent and paintComponents in Swing

Java Swing中paint()paintComponent()paintComponents()之间的实际区别是什么?

我试图了解Oracle文档中的解释,但不清楚。


  • AWT,覆盖paint()
  • 摆动顶层容器(例如JFrameJWindowJDialogJApplet ..),覆盖paint()。 但是,有许多充分的理由不采用TLC进行涂漆。 也许是一个单独问题的主题。
  • Swing的其余部分(从JComponent派生的任何组件)将覆盖paintComponent()
  • 既不覆盖也不显式调用paintComponents(),将其留给API以在需要时调用它。

确保覆盖方法时也使用@Override表示法。

这样做将提示尝试覆盖JFrame中的paintComponent(..)的问题(它没有这样的方法),这很常见。


您可能有兴趣阅读AWT和Swing中的绘画

引用:

The rules that apply to AWT's lightweight components also apply to Swing components -- for instance, paint() gets called when it's time to render -- except that Swing further factors the paint() call into three separate methods, which are invoked in the following order:

1
2
3
 protected void paintComponent(Graphics g)
protected void paintBorder(Graphics g)
protected void paintChildren(Graphics g)

Swing programs should override paintComponent() instead of overriding paint(). Although the API allows it, there is generally no reason to override paintBorder() or paintComponents() (and if you do, make sure you know what you're doing!). This factoring makes it easier for programs to override only the portion of the painting which they need to extend. For example, this solves the AWT problem mentioned previously where a failure to invoke super.paint() prevented any lightweight children from appearing.