java label刷新,如何在java fx中每2秒更新一次标签框?

I'm trying to simulate a basic thermostat in an application GUI.

I want to update a label box value every 2 secs with the new temperature value.

For example, my intial temperature will be displayed as 68 degrees and updated to 69, to 70, etc. till 75 every 2 seconds.

This is a piece of code I wrote in Java fx. controlpanel is object of te form where the label box is present. It updates only the final value as 75. It doesnt update it every 2 secs. I have written a method pause to cause a 2 secs delay. All labels are updated with their final values but not updated every 2 secs. When I debug, I can see that the values are increased by one every 2 secs. This code is written in button onClick event

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

int i=0;

Timer asd = new Timer(1000,null);

asd.setDelay(1000);

while(i < 10)

{

jTextField1.setText(Integer.toString(i));

i++;

asd.start();

}

}

解决方案

To solve your task using Timer you need to implement TimerTask with your code and use Timer#scheduleAtFixedRate method to run that code repeatedly:

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

@Override

public void run() {

System.out.print("I would be called every 2 seconds");

}

}, 0, 2000);

Also note that calling any UI operations must be done on Swing UI thread (or FX UI thread if you are using JavaFX):

private int i = 0;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

@Override

public void run() {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

jTextField1.setText(Integer.toString(i++));

}

});

}

}, 0, 2000);

}

In case of JavaFX you need to update FX controls on "FX UI thread" instead of Swing one. To achieve that use javafx.application.Platform#runLater method instead of SwingUtilities

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值