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.
It looks like the paint() method actually draws the component, including the border and children. If you only want to customize the component's appearance excluding the border and children, you use paintComponent() .
The paint() method contains instructions for painting the specific component. The repaint() method, which can't be overridden, is more specific: it controls the update() to paint() process. You should call this method if you want a component to repaint itself or to change its look (but not the size).
repaint() calls the paintComponent() method. Every time you wish to change the appearance of your JPanel, you must call repaint().
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 .)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With