Difference between paint() and paintcomponent()?
Solution 1
Quoting from documentation of paint()
method
This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. ... A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent.
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()
.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#paint(java.awt.Graphics)
Solution 2
Generally speaking, when painting in Swing, it is recommended to override paintComponent
.
There are a number of reasons why, one is paintComponent
is painted at the bottom layer, meaning you won't accidentally wiping out any components that were rendered during the paint process - this happens a lot to people who post here.
There are a, very, few times you might need to override paint
, but I would always encourage you to try making it work with paintComponent
first.
Check out
- Performing custom painting
- Painting in AWT and Swing (+1 to trashgod)
Related videos on Youtube
Boogley Beegly
Updated on June 21, 2022Comments
-
Boogley Beegly about 2 years
I have tried tutorials on this but I still don't quite understand it. Basically my question is which method is better and why? Should I use
paint
orpaintComponent
?Please try to keep the answer simple, thanks.
-
trashgod over 11 yearsSee also Painting in AWT and Swing.
-
-
MadProgrammer over 11 yearsWhile correct, it would be prudent to link to a more to update version of the JavaDocs, just to highlight to developers potential changes to the API
-
christianhs over 11 yearsI edited the link. thanks @MadProgrammer for reminding me about this
-
MadProgrammer over 11 yearsStill got a +1 for the answer regardless ;)
-
camickr over 11 yearsI don't think it matters if you override paint() or paintComponent() from a double buffering point of view. See the double buffering section from the "Painting in AWT and Swing" article. Now if you happen to override paint() at a frame level (which I never recommend) and forget about invoking super.paint() then you can get into some trouble.
-
MadProgrammer over 11 years@camickr Ah yes, you're right, that's the argument for not overriding top level containers :P