yvoytovych
yvoytovych

Reputation: 871

Java Swing with multiple threads

The problem is: i have a swing app. Only one form with 2 btns ("Start","Stop"). On these btns i added ActionListener with thread class inside.

I want to start in new thread some work when i click btn "Start" and end that work when i click btn "Stop". Code a little bit similar to this works ok in console, but in swing doest. Any help appreciated. Thanks in advance. )

    class Action implements ActionListener{
        class MyThread extends Thread{
             boolean live = true;

             @Override
             public void run() {            
                while(live)
                     System.out.println("doing...");
             }              

              public void shutDown(){   
                 live = false;
             }
        }
        @Override
        public void actionPerformed(ActionEvent e) {
             JButton source = (JButton) e.getSource();
             MyThread t = new MyThread();
             switch (source.getText()) {
             case "Start":
                  t.start();
                  break;
             case "Stop":
                  t.shutDown();
                  break;
    }

And that simple form

    public class App extends JFrame {
        public static void main(String[] args) {
            App app = new App();
            app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            app.setVisible(true);

            JButton btn1 = new JButton("Start");
            JButton btn2 = new JButton("Stop");

            app.getContentPane().add(btn1, BorderLayout.WEST);
            app.getContentPane().add(btn2, BorderLayout.EAST);

            Action action = new Action();

            btn1.addActionListener(action);
            btn2.addActionListener(action);
        }

    }

Upvotes: 2

Views: 1119

Answers (1)

Adrian
Adrian

Reputation: 46413

You're creating a new Thread object every time a button is clicked, so the thread you stop isn't the same one that you started. You'll need to keep a reference to the thread you created on start so that you can stop it again later.

Upvotes: 2

Related Questions