Question

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.

Was it helpful?

Solution

  • AWT, override paint().
  • Swing top-level container (e.g.s are JApplet, JFrame, JWindow, JDialog..), 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, 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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top