Search code examples
javamultithreadingswingactionlistenerillegalstateexception

IllegalStateException: Same thread, different source (GUI)


my problem is that I want to add the same ActionListener to 2 different components on my GUI program. One, when the user presses Enter Key in a JTextField, and the second when the user clicks on a JButton. I am using the Netbeans IDE.

So I created a Thread, t1, and in the actionListener's actionPerformed method, I simply put t1.start(). Then I added the actionListener object to my JTextField and my JButton. When I run the program, the first time I either click the button or press Enter, the program runs smoothly. But on the second time I click the button or press Enter, the program throws an IllegalStateException. Here is my code:

    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.
    }

I am thinking that the thread did not 'die' from the first time I clicked or pressed Enter, even though the run() method already exited. I tested the program at different points to make sure that the run() method did exit.

I am able to make program work if I create a thread in both the JButtonActionPerformed( and JTextFieldActionPerformed() methods, and start them inside these methods itself. But it's redundant since I am writing the same actions to be performed in 2 different methods.

Any help on why the IllegalStateException exception was thrown and on how to create a single ActionListener for both the JComponents using a thread is appreciated. Thanks!


Solution

  • As the JavaDocs state...

    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.

    You can not start a Thread twice. Instead, start with a Runnable and wrap a new Thread around it each time you want to run it