确定事件调度线程的范围

Sur*_*ran 1 java swing multithreading event-handling event-dispatch-thread

我是新手,还在学习它的来龙去脉.我写了一个基本代码并开始尝试EDT.这是代码:

public class SwingDemo2 extends Thread implements ActionListener {

JLabel jl;

SwingDemo2() {
    JFrame jfr = new JFrame("Swing Event Handling");
    jfr.setSize(250, 100);
    jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    jl = new JLabel("Press a button!", SwingConstants.CENTER);

    System.out.println("After Label: " + SwingUtilities.isEventDispatchThread());

    JButton jb1 = new JButton("OK");
    jb1.setActionCommand("OK");

    jb1.addActionListener(this);

    JButton jb2 = new JButton("Reset");
    jb2.setActionCommand("Reset");

    jb2.addActionListener(this);

    jfr.add(jl, BorderLayout.NORTH);
    jfr.add(jb1, BorderLayout.WEST);
    jfr.add(jb2, BorderLayout.EAST);

    System.out.println("After adding: " + SwingUtilities.isEventDispatchThread());

    jfr.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            System.out.println("In main: " + SwingUtilities.isEventDispatchThread());
            new SwingDemo2();
        }
    });
}

public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand() == "OK") {
        System.out.println("In OK: " + SwingUtilities.isEventDispatchThread());
        jl.setText("You pressed Ok");
    }
    else if (ae.getActionCommand() == "Reset") {
        System.out.println("In Reset: " + SwingUtilities.isEventDispatchThread());
        jl.setText("You pressed Reset");
    }

}

}
Run Code Online (Sandbox Code Playgroud)

我添加了一些isEventDispatchThread()方法来验证我所在的线程.除了GUI,控制台中的消息是:

In main: true
After Label: true
After adding: true
In OK: true
In Reset: true
Run Code Online (Sandbox Code Playgroud)

似乎我一直在美国东部时间.我的问题是,在jfr.setVisible(true)声明之后,SwingDemo2()构造函数不应该返回main()并且不应该是EDT的结束吗?

在我第一次按下GUI中的任何按钮之前,我等了好几秒钟,为什么我的事件处理仍在EDT中完成?难道不应该让EDT有足够的时间终止吗?

Thanx提前!

Gui*_*let 5

在事件调度线程中,您会看到"事件"一词.这意味着所有(UI)"事件"总是在该特定线程上调度:ActionEvent,PaintEvent,KeyEvent,MouseEvent等...您可以等待所需的时间,将始终调度按钮单击(ActionEvent)美国东部时间.

当JVM启动时,它会调用main()"Main"-Thread上的方法.在其中,你使用SwingUtilities.invokeLater()哪个将启动EDT并且Runnable你提供的将被执行(在EDT的范围内).与此同时,您的主线程在到达其最后一个语句后停止运行.另一方面,EDT永远不会停止运行并不断等待新事件发生.