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

标签 java

因此,首先我创建了一个 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/

相关文章:

java - 从 QBytearray 创建 QImage

java - 比较通过套接字 UTF8 传递的字符串

java - onErrorMap 和 onErrorContinue

java - 完成后以编程方式关闭 ACTION_VIEW 对话框

java - JMeter:使用 java 类为自定义 header 生成值

java - XPages - docx4j - 用文本替换书签

java netbeans 命令行参数传递

java - 日期格式映射到 JSON Jackson

java - 解析制表符分隔文件的策略

java - 如何动态创建XML(java)?