谁在我的类中调用paintComponent()方法? [英] Who is calling the paintComponent() method in my class?
问题描述
我有一个简单的类,用于在JPanel中绘制图形。这是我的班级:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
class Drawing_panel扩展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);
}
}
我有另一个实例化这个的类:
Drawing_panel dp = new Drawing_panel();
Drawing_panel
类中没有构造函数和/或没有显式调用 paintComponent()
或 getPreferredSize()
方法。我假设该方法是在父 JPanel
构造函数中调用的,但是我没有看到那里的调用。
从几个不同的地方调用 paintComponent
。来自 JComponent.paint
的调用可能是您正在寻找的。 p>
请注意 paintComponent
未从任何构造函数调用。 paintComponent
被称为按需,即当系统决定需要重新绘制该组件时。 (例如,可以在调整组件大小时,或者从最小化状态恢复窗口时。)要清楚:组件不是涂漆,然后使用,而是使用,然后在需要时涂漆。 / p>
这整个绘画调用链都不是你应该打扰的,因为它完全由Swing和所谓的事件调度线程完成。
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 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.
这篇关于谁在我的类中调用paintComponent()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!