简体   繁体   English

如何在不冻结 GUI 的情况下运行它

[英]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.如果按下按钮,GUI 会冻结。 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?为什么 GUI 会冻结?

Don't call run() directly on your Thread object.不要直接在Thread对象上调用run() This immediately executes the run() method and doesn't spawn a new thread.这会立即执行run()方法并且不会产生新线程。 Instead, just call start() as you have and let the system create the thread and call run() when it decides to.相反,只需调用start()并让系统创建线程并在它决定时调用run()

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.还值得指出的是,在 Swing 中安排图形工作的正确方法是确保它以事件调度线程结束。 To do this properly, use SwingUtilities#invokeLater(Runnable) , which will not wait for the work to complete, or SwingUtilities#invokeAndWait(Runnable) , which will.要正确执行此操作,请使用SwingUtilities#invokeLater(Runnable) ,它不会等待工作完成,或者使用SwingUtilities#invokeAndWait(Runnable)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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