简体   繁体   中英

Is calling super.paintComponent() important?

What is the importance of calling the paintComponent method defined it the super class when overriding it in a subclass. I couldn't grasp the reason. For example: see the code below here for displaying filled arcs:

package graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.Color;
import java.awt.Graphics;

@SuppressWarnings("serial")
class DrawArcs2 extends JFrame {

    public DrawArcs2() {
        setTitle("The Four Fan Blades");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        add(new BladesPanel());
    }

    class BladesPanel extends JPanel {
        protected void paintComponent(Graphics g){
            super.paintComponent(g);
            g.setColor(Color.MAGENTA);

            int xCenter = getWidth() / 2;
            int yCenter = getHeight() / 2;
            int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);

            int x = xCenter - radius;
            int y = yCenter - radius;

            g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
            g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
            g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
            g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
        }
    }

    public static void main(String[] args) {
        DrawArcs2 fanBlades = new DrawArcs2();
        fanBlades.setSize(300,300);
        fanBlades.setVisible(true);
    }
}

The short answer is yes, it's important.

One of the jobs of paintComponent is to prepare the Graphics context for painting, this is typically done by filling the Graphics context with the background color of the current component.

But, more importantly, it's one of the methods that forms a chain of paint methods, which together produce the painting outcome, you should continue to maintain that link incase the paintComponent method is changed in the future or the component you've extending from does other work with it (like JTable for example)

Failing to call it could result in any number of Graphics glitches and artifacts which are difficult to trace and even produce reliably

Take a look at Painting in AWT and Swing and Performing Custom Painting for more details about the painting process

Usually it is important. If it is not declared most of the objects that it encompasses will not be accessible. It is kinda like an object. You need to declare it to call other functions of that class.

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