Search code examples
javaswingevent-dispatch-thread

How can I get this to run without freezing the GUI


This is a very simplified version of my code to get a better understanding of what I'm doing wrong here. The GUI freezes if the button is pressed. I need to be able to run a while loop if the button is pressed without freezing.

class obj1 extends Thread{
    public void run(){
        while(true) {
            System.out.println("this thread should run when the button is pressed and I should be able to press another button");
        }
    }
}

class GUI extends Thread{
    JFrame frame = new JFrame();
    JButton button = new JButton("test1");
    JButton button2 = new JButton("test2");
    JPanel panel = new JPanel();
    String command;

    public void run() {
        frame.setVisible(true);
        panel.add(button);
        panel.add(button2);
        frame.add(panel);
        frame.pack();

        buttonOnAction();
    }


    public void buttonOnAction(){
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                obj1 one = new obj1();
                one.start();
                one.run();
            }
        });

        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                obj1 one2 = new obj1();
                one2.start();
                one2.run();

            }
        });
    }
}


public class Main{

    public static void main(String args[]){
            GUI gui = new GUI();
            gui.start();
            gui.run();
   }
}

Why does the GUI freeze?


Solution

  • Don't call run() directly on your Thread object. This immediately executes the run() method and doesn't spawn a new thread. Instead, just call start() as you have and let the system create the thread and call run() when it decides to.