How to make a thread not freeze you whole JFrame. JAVA

醉酒当歌 提交于 2019-11-26 22:00:30

问题


Hey i just need a question answered... How would i make the following code not freeze my whole JFrame?

                try {
                Thread.sleep(Integer.parseInt(delayField.getText()) * 1000);
                System.out.println("Hello!");
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

回答1:


use a different thread to perform this task. If you do this in the main UI thread then it will freeze.. For example you can do following

  new Thread() {

        @Override
        public void run() {
            try {
                Thread.sleep(Integer.parseInt(delayField.getText()) * 1000);
                System.out.println("Hello!");
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

        }
    }.start();

UPDATE

AFter wise suggestions of Robin and Marko I am updating the answer with a better solution.

    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
                System.out.println("Hello!");

        }
    };
    javax.swing.Timer t = new javax.swing.Timer(Integer.parseInt(delayField.getText()) * 1000, taskPerformer);
    t.setRepeats(false);
    t.start();



回答2:


Whenever you are about to use Thread.sleep in your GUI code, stop yourself and think of Swing Timer, which is the right tool for the job. Schedule the task you need to perform with a delay.

Using another thread for this is not the best advice: it wastes a heavy system resource (a thread) to do absolutely nothing but wait.




回答3:


This is not the correct way to use threads in java . You should use swingutilities.invokelater

swing utils invoke later




回答4:


You don't want to execute this on the UI (or event dispatch thread) thread. Rather in a separate thread. Otherwise (as you've seen) you'll block the UI.

It's a good practice to perform time-consuming operations on a separate thread, and make use of SwingUtilities.invokeLater() if those threads need to perform some subsequent UI action (e.g. in the above display "Hello" in the UI)



来源:https://stackoverflow.com/questions/16788384/how-to-make-a-thread-not-freeze-you-whole-jframe-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!