Difference between paint, paintComponent and paintComponents in Swing

痞子三分冷 提交于 2019-11-25 22:13:08
  • AWT, override paint().
  • Swing top-level container (e.g.s are JApplet, JFrame, JWindow, JDialog..), override paint(). But there are a number of good reasons not to paint in a TLC. A subject for a separate question, perhaps.
  • The rest of Swing, override paintComponent().
  • Neither override nor explicitly call paintComponents(), leave it to the API to call it when needed.

Be sure to also use @Override notation whenever overriding a method.

Doing so would hint at the problem of trying to override paintComponent(..) in a JFrame (it has no such method), which is quite common to see.

Avrom

You may be interested in reading Painting in AWT and Swing

A quote:

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:

 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!