简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM