简体   繁体   中英

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

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

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

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.

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

swing utils invoke later

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 (eg in the above display "Hello" in the UI)

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