因此,首先我创建了一个 JFrame 对象,然后创建了一个使用 PaintComponent 方法的适当重写版本来扩展 JComponent 的类。
最后,我将此类的一个对象添加到 JFrame 对象中。
引用代码如下:
import java.awt.*;
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
MyComponent comp = new MyComponent();
frame.add(comp);
}
}
class MyComponent extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Rectangle r = new Rectangle(0,0,100,100);
g2.draw(r);
}
}
我的问题是...paintComponent
方法采用 Graphics2D 对象作为参数,但是谁传递了这个对象,因为我不是。
最佳答案
My question is...the
paintComponent
method takes a Graphics2D object as it's argument, but who is passing this coz I'm not.
当在 EDT 上处理绘制事件时,绘制系统会将其传入。 .
在许多方面,paintComponent
与其他事件处理程序(actionPerformed
、itemStateChanged
等)类似,因为您无需调用它明确地。系统准备传递给您的对象(在本例中为Graphics
)并在需要时调用它。
[If] the paint request originates on the first heavyweight ancestor (usually
JFrame
,JDialog
,JWindow
, orJApplet
):
the event dispatching thread invokes
paint()
on that ancestorThe default implementation of
Container.paint()
recursively callspaint()
on any lightweight descendents[If] the paint request originates from a call to
repaint()
on an extension ofjavax.swing.JComponent
:
JComponent.repaint()
registers an asynchronous repaint request to the component'sRepaintManager
, which usesinvokeLater()
to queue aRunnable
to later process the request on the event dispatching thread.The runnable executes on the event dispatching thread and causes the component's
RepaintManager
to invokepaintImmediately()
on the component, which [...] invokespaint()
on the root component.
(并且 paintComponent
由 paint
调用。)
关于Java 图形用户界面 : paintComponent method in the JComponent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29267826/