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

问题描述 投票:0回答:2

这是我的代码的非常简化的版本,可以更好地了解我在这里做错了什么。如果按下该按钮,则GUI冻结。如果按下按钮时没有冻结,我需要能够运行while循环。

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冻结?

java swing event-dispatch-thread
2个回答
0
投票
graphical工作的正确方法是确保它在事件分发线程中结束。要正确执行此操作,请使用SwingUtilities#invokeLater(Runnable)(不会等待工作完成),或使用SwingUtilities#invokeLater(Runnable)(会等待工作完成)。
© www.soinside.com 2019 - 2024. All rights reserved.