[Solved] Is `super.paintComponent(g)` mandatory?

I was taught in my class and also seen in this book (Big Java Early Objects) to include draw instructions in a class extending JComponent as:

public class Component extends JComponent {
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        Rectangle r = new Rectangle(0,0,20,10);
        g2.draw(r);
    }
}

However, someone pointed out that the first line in the paintComponent method should be: super.paintComponent(g);

Based on my limited knowledge, I believe it’s calling JComponent’s version of the method (now overridden). Why does this need to happen? What happens if I just ignore this statement as I’ve been doing until now?

Solution #1:

Why does this need to happen? What happens if I just ignore this statement as I’ve been doing until now?

A component is responsible for painting itself completely. The default painting may be different for each LAF, so by invoking super.paintComponent() you make sure you get the default painting which will basically just be the background.

If you don’t invoke this method you have the potential for painting artifacts to occur. Then may not always occur, but you don’t want to waste time debugging.

Read the API for the paintComponent() method of JComponent. Among other things it states:

Further, if you do not invoker super’s implementation you must honor the opaque property, that is if this component is opaque, you must completely fill in the background in a non-opaque color. If you do not honor the opaque property you will likely see visual artifacts.

So at a minimum you need:

g.fillRect(0, 0, getWidth(), getHeight());

to make sure the background is cleared before you start your custom painting.

Respondent: camickr

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.