A
A
Andrey Begin2018-09-21 13:35:39
Java
Andrey Begin, 2018-09-21 13:35:39

What is the difference between paint & paintComponents?

Wrote a small piece of code for an image rendering test

import javax.swing.*;
import java.awt.*;

public class MainWindow extends JFrame {

    private Image avt;

    public MainWindow()
    {
        setSize(800, 500);
        setLocation(500, 0);
        setVisible(true);

        load_img();
    }
    public void load_img()
    {
        ImageIcon avatar = new ImageIcon("avatar.png");
        avt = avatar.getImage();
    }

    public void paintComponents(Graphics g) {
        super.paintComponents(g);
        g.drawImage(avt, 0, 20, this);
    }

    public static void main(String[] args)
    {
        MainWindow mw = new MainWindow();
    }
}

However, paintComponents just doesn't work in this case.
If you replace it with paint, then everything will be drawn accordingly.
So what's the actual difference? And why doesn't paintComponents even run during code execution in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Alexandrov, 2018-09-21
@jamakasi666

In general, there are tons of reflections and implicit calls in awt and swing, the topic is rather complicated, to put it simply. A little
well chewed here .
Specifically, you are probably missing the override annotation and there is an error in the name of the method in the form of an extra letter at the end of paintComponentS . Well, I'm not completely sure either. I don’t remember exactly, but it seems that paintComponent is called when the component is completely rendered, which is rare. the rest of the time the paint method will twitch in which there is no your picture. Something like this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question