Reputation: 8385
What is the actual difference between paint()
, paintComponent()
and paintComponents()
in Java Swing?
I tried to understand what explained in Oracle docs but I am not clear.
Upvotes: 33
Views: 36870
Reputation: 168815
paint()
.JFrame
, JWindow
, JDialog
, JApplet
..), override paint()
. But there are a number of good reasons not to paint in a TLC. A subject for a separate question, perhaps.JComponent
), override paintComponent()
.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.
Upvotes: 44
Reputation: 5027
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.
Upvotes: 20