33

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.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
Abhishek Choudhary
  • 7,569
  • 18
  • 63
  • 118

2 Answers2

42
  • 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.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
  • Hi, is paint() function get called immediately after constructor finish execute? – Sam YC Nov 27 '12 at 02:17
  • 1
    @GMsoF `repaint()` will be called automatically when needed. If animating, it might also be called explicitly. Though called too many times, too quickly, and some calls will be coalesced (ignored). – Andrew Thompson Nov 27 '12 at 03:29
  • also override paint() if you want to draw something on your jpanel subclass that is ABOVE components on the same panel - for example, if GPanel is a your subclass of JPanel, by overriding only paintComponent, your "drawings" will be located behind any components such as buttons, other panels, etc. However, using paint(), you draw "over" the other components. – PixelMaster Mar 15 '16 at 15:27
20

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.

Force444
  • 2,872
  • 7
  • 31
  • 70
Avrom
  • 4,607
  • 2
  • 25
  • 35