Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between paint, paintComponent and paintComponents in Swing

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.

like image 749
Abhishek Choudhary Avatar asked Feb 22 '12 04:02

Abhishek Choudhary


People also ask

What is the difference between paint and 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() .

What is the difference between the paint () and repaint () methods?

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).

Does repaint call paintComponent?

repaint() calls the paintComponent() method. Every time you wish to change the appearance of your JPanel, you must call repaint().

What is paintComponent mean?

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 .)


1 Answers

  • AWT, override paint().
  • Swing top-level container (e.g.s are 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.
  • The rest of Swing (any component that derives from JComponent), 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.

like image 177
Andrew Thompson Avatar answered Oct 09 '22 08:10

Andrew Thompson