简体   繁体   English

如何在循环中更改JLabel的文本而不切换得使用户看不到它呢?

[英]How to change a JLabel's text in a loop without switching so fast the user can't see it?

I want to create a simple clock using Java. 我想使用Java创建一个简单的时钟。 The code is so simple that I will give an example: 代码非常简单,我将举一个例子:

for(int i=0;i<=60;i++)
   jLabel11.setText( Integer.toString(i) );

The problem is while I'm running my program the result didn't show each update in sequence. 问题是当我运行程序时,结果没有按顺序显示每个更新。 It show only the 60 digit immediately, without showing the change from 1 to 2 to 3 ... 它仅立即显示60位数字,而不显示从1到2到3的变化...

How can i fix this problem? 我该如何解决这个问题?

The problem is that changes to the UI should run on the event dispatch thread, but blocking this loop (and blocking the UI) will stop the screen from repainting. 问题在于对UI的更改应在事件分发线程上运行,但是阻止此循环(和阻止UI)将阻止屏幕重新绘制。 Instead, use a timer to perform regular updates, eg 而是使用计时器执行定期更新,例如

Timer timer = new Timer();

ActionListener updater = new ActionListener()
{
   int count;
   public void actionPerformed(ActionEvent event) {
      jLabel11.setText( Integer.toString(count++) );
      if (count==60)
         timer.stop();
   }
}
timer.setDelay(100);
timer.addActionListener(updater);
timer.start(); 

See the Sun Tutorial - How to use Swing Timers . 请参见《 Sun教程- 如何使用Swing计时器》

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

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