繁体   English   中英

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

[英]How can I get this to run without freezing the GUI

这是我的代码的一个非常简化的版本,以便更好地了解我在这里做错了什么。 如果按下按钮,GUI 会冻结。 如果按下按钮而不冻结,我需要能够运行一段时间循环。

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();
   }
}

为什么 GUI 会冻结?

不要直接在Thread对象上调用run() 这会立即执行run()方法并且不会产生新线程。 相反,只需调用start()并让系统创建线程并在它决定时调用run()

还值得指出的是,在 Swing 中安排图形工作的正确方法是确保它以事件调度线程结束。 要正确执行此操作,请使用SwingUtilities#invokeLater(Runnable) ,它不会等待工作完成,或者使用SwingUtilities#invokeAndWait(Runnable)

暂无
暂无

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

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