简体   繁体   English

JLabel是否不需要其他线程即可刷新?

[英]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. 我一辈子都想不通如何刷新JLabel。 I've searched other threads, but they all involve using additional threads. 我搜索了其他线程,但是它们都涉及使用其他线程。 Is there a way to make either the JLabel/Panel refresh? 有没有办法使JLabel / Panel刷新? (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. 如果我删除了while循环,它会起作用,这只会给我原始时间的计时器String,并且不会减少。 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. 但是,如果我包含while循环,它只会返回一个恒定的黑屏,直到计时器用完为止,然后它会返回原始值。

How should I refresh the JLabel so that it will display to the GUI every time it decrements (hopefully without using threads..) ? 我应该如何刷新JLabel,以使其在每次递减时都显示在GUI上(希望不使用线程。)? (Or every time the while loop runs) (或者每次while循环运行时)

"It works if I remove the while loop " “如果删除while循环,它将起作用

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. Swing是一个单线程框架,这意味着EDT阻止的任何块都将阻止处理事件队列并导致UI挂起。

See Concurrency in Swing for more details. 有关更多详细信息,请参见Swing中的并发

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. 最简单的解决方案是使用Swing Timer ,它将允许您安排将在EDT上下文中执行的常规回调。

See How to use Swing Timers for more details 有关更多详细信息,请参见如何使用Swing计时器

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

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

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