gpt4 book ai didi

Java 图形用户界面 : paintComponent method in the JComponent class

转载 作者:行者123 更新时间:2023-11-30 08:54:58 34 4
gpt4 key购买 nike

因此,首先我创建了一个 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 与其他事件处理程序(actionPerformeditemStateChanged 等)一样,您无需调用它明确地。系统准备传递给您的对象(在本例中为 Graphics)并在需要时调用它。

摘自 Painting in AWT and Swing :

[If] the paint request originates on the first heavyweight ancestor (usually JFrame, JDialog, JWindow, or JApplet):

  • the event dispatching thread invokes paint() on that ancestor

  • The default implementation of Container.paint() recursively calls paint() on any lightweight descendents

[If] the paint request originates from a call to repaint() on an extension of javax.swing.JComponent:

  • JComponent.repaint() registers an asynchronous repaint request to the component's RepaintManager, which uses invokeLater() to queue a Runnable 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 invoke paintImmediately() on the component, which [...] invokes paint() on the root component.

(并且 paintComponentpaint 调用。)

关于Java 图形用户界面 : paintComponent method in the JComponent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29267826/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com