简体   繁体   中英

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?

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.

It is also worth pointing out that the proper way to schedule graphical work in Swing is to make sure it ends up on the event dispatch thread. To do this properly, use SwingUtilities#invokeLater(Runnable) , which will not wait for the work to complete, or SwingUtilities#invokeAndWait(Runnable) , which will.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM