简体   繁体   中英

JLabel not refreshing without needing additional threads?

I'm making a countdown timer which refreshes every second.

I can't figure out for the life of me how to make the JLabel refresh. I've searched other threads, but they all involve using additional threads. Is there a way to make either the JLabel/Panel refresh? (Panel may be unnecessary). It works if I remove the while loop, which would just give me a still String of the timer at its original time, with no decrement. But if I include the while loop, it just returns a constant blank screen until the timer runs out, then it goes back to the original value.

How should I refresh the JLabel so that it will display to the GUI every time it decrements (hopefully without using threads..) ? (Or every time the while loop runs)

"It works if I remove the while loop "

You're blocking the event dispatching thread.

Swing is a single threaded framework, that means that anything the blocks the EDT will prevent from processing the Event Queue and cause the UI to hang.

See Concurrency in Swing for more details.

The simplest solution would be to use a Swing Timer , which will allow you to schedule a regular callback which will be executed from within the context of the EDT.

See How to use Swing Timers for more details

javax.swing.Timer timer = new javax.swing.Timer(500, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        counter++;
        label.setText(count);
    }
});

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