开发者

Who is calling the paintComponent() method in my class?

I have a simple class that paints a graphic in a JPanel. This is my class:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;

class Drawing_panel extends JPanel {
    public void paintComponent(Graphics g) {
    super.paintComponent(g);       
    this.setBackground(Color.white);
    g.setColor(Color.red);
    g.fillRect(150, 80, 20, 20);
}  

public Dimension getPreferredSize(){
    return new Dimension(500,500);
}

}

I have another class that instantiates this one:

Drawing_panel dp = new Drawing_panel();

There is no constructor开发者_Python百科 in the Drawing_panel class and/or no explicit call to either the paintComponent() or getPreferredSize() methods. I assume the method is being called in the parent JPanel constructor, but I did not see the calls there either.


The paintComponent is called from a few different places. The call from JComponent.paint is probably the one you're looking for.

Note that paintComponent is not called from any constructor. The paintComponent is called "on-demand" i.e. when the system decides that the component needs to be redrawn. (Could for instance be when the component is resized, or when the window is restored from a minimized state.) To be clear: The component is not "painted, then used", it is "used, then painted when needed".

This whole chain of painting-calls is nothing you should bother about, as it is taken care of entirely by the Swing and the so called Event Dispatch Thread.


When you subclass JComponent or JPanel to draw graphics, override the paintComponent() method. This method is called because the user did something with the user interface that required redrawing, or your code has explicitly requested that it be redrawn. Called automatically when it becomes visible When a window becomes visible (uncovered or deminimized) or is resized, the "system" automatically calls the paintComponent() method for all areas of the screen that have to be redrawn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜