Difference between paint, paintComponent and paintComponents in Swing
Solution 1:
- AWT, override
paint()
. - Swing top-level container (e.g.s are
JFrame
,JWindow
,JDialog
,JApplet
..), overridepaint()
. 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 (any component that derives from
JComponent
), overridepaintComponent()
. - 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.
Solution 2:
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.