【问题标题】:Does actionPerformed(ActionEvent e) runs in a different thread than the Event Dispatch Thread (EDT)?actionPerformed(ActionEvent e) 是否在与事件调度线程 (EDT) 不同的线程中运行?
【发布时间】:2014-09-23 05:21:37
【问题描述】:

actionPerformed(ActionEvent e) 是否在与事件调度线程 (EDT) 不同的线程中运行? 假设我写了以下代码:

public void main(String args[]){
     EventQueue.invokeLater(new Runnable() {
        public void run() {
            try { 
                  Frame f = new Frame();
                  f.setVisible(true);
                  javax.swing.SwingUtilities.isEventDispatchThread()
                }
            catch(Exception e){ e.printStackTree;}
}

public Frame()
{ //...some code....

    JButton btn = new JButton();
    //int a;
    javax.swing.SwingUtilities.isEventDispatchThread()
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) { 
            //..some code....
            javax.swing.SwingUtilities.isEventDispatchThread()
            //a++;
        }
    }
}

虽然运行 javax.swing.SwingUtilities.isEventDispatchThread() 在所有三种情况下都返回 true,但在 actionPreformed 中执行 a++ 是不可能的。

我调试了这个项目,如果我错了,请纠正我:尽管整个框架是在 EDT 内运行的,但 EDT 为 Frame() 构造函数和 actionPreformed() 函数启动了新的不同线程。然后,正因为如此,为了避免 actionPreformed() 将使用在另一个线程中创建的变量 a 可能在 actionPreformed() 的线程之前结束,它不可能将 a 作为常规 '' int'',只允许''final int''。

1 那么本例中的 actionPrefromed() 函数是否在与 Frame() 构造函数的线程不同的线程中运行?

1.1 如果不是,那为什么不能在 actionPreformed() 函数中修改 a 呢?

1.2 如果是,那么我如何存储可以保存在 Frame() 构造函数中的值?或者至少可以通过其他不同的按钮访问?

2 为什么首先要在 ETD 内部创建框架 f,或者将其设置为可见?

【问题讨论】:

  • 太多问题...您最初的问题与您的以下问题无关...对于您的第一个问题:ActionPerformed 在 edt 中运行。

标签: java swing event-dispatch-thread


【解决方案1】:

问题不在于线程,而在于匿名 ActionListener 类就是这样 - 一个不同的类。 ActionListener 的生命周期比局部变量 'a' 的生命周期长,所以你不能修改它。因此,它必须是最终的。

实际上,尝试“在构造函数中保留一个变量”,然后允许一个寿命更长的类来修改它,这实际上是绝对没有意义的。

我相信最接近您想要的是将“a”设为 Frame 类的成员变量。然后,如果必须,您可以在 ActionListener 中使用“Frame.this.a”访问它,但在 Frame 中使用公共方法会更好。

最后,在 EDT 上创建框架并将其设置为“可见”,因为这是唯一可以安全修改 Swing 组件的线程。

【讨论】:

    猜你喜欢
    • 2011-01-27
    • 1970-01-01
    • 2013-01-02
    • 2011-01-08
    • 2011-05-25
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多