IllegalStateException:相同线程,不同来源 (GUI)

IllegalStateException: Same thread, different source (GUI)

我的问题是我想将相同的 ActionListener 添加到我的 GUI 程序上的 2 个不同组件。一种是当用户在 JTextField 中按下 Enter 键时,第二种是当用户单击 JButton 时。我正在使用 Netbeans IDE.

所以我创建了一个Thread,t1,在actionListener的actionPerformed方法中,我简单地输入了t1.start()。然后我将 actionListener 对象添加到我的 JTextField 和我的 JButton。 当我 运行 程序时,第一次单击按钮或按 Enter 时,程序 运行 很顺利。但是在我第二次单击按钮或按 Enter 时,程序抛出 IllegalStateException。 这是我的代码:

    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            //Do something
        }
     });
    public final ActionListener listener;

    public myClass () {    //Constructor 
        this.listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                t1.start();
            }
        };
    InitComponents();
    JButton.addActionListener(listener);      //Adding listener object to JButton.
    JTextField.addActionListener(listener);   //Adding listener object to JTextField.
    }

我在想,从我第一次单击或按下 Enter 开始,线程就没有 'die',即使 运行() 方法已经退出。我在不同的点测试了程序,以确保 运行() 方法确实退出了。

如果我在 JButtonActionPerformed(JTextFieldActionPerformed() 方法中创建一个线程,我就能使程序工作,并开始它们在这些方法本身中。但这是多余的,因为我正在编写要在 2 种不同方法中执行的相同操作。

对于抛出 IllegalStateException 异常的原因以及如何使用线程为两个 JComponents 创建单个 ActionListener 的任何帮助,我们将不胜感激。 谢谢!

作为 JavaDocs 状态...

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Throws:
IllegalThreadStateException - if the thread was already started.

你不能start一个Thread两次。相反,从 Runnable 开始,每次你想要 运行 it

时在其周围包裹一个新的 Thread