如何在java fx中每2秒更新一次标签框? [英] How to update the label box every 2 seconds in java fx?
问题描述
我正在尝试在应用程序GUI中模拟基本恒温器。
I'm trying to simulate a basic thermostat in an application GUI.
我想用新的温度值每2秒更新一个标签盒值。
I want to update a label box value every 2 secs with the new temperature value.
例如,我的初始温度将显示为68度并更新为69,至70等等,每2秒更新75次。
For example, my intial temperature will be displayed as 68 degrees and updated to 69, to 70, etc. till 75 every 2 seconds.
这是我在Java fx中编写的一段代码。 controlpanel
是te形式的对象,其中存在标签框。它仅将最终值更新为75.它不会每2秒更新一次。我写了一个方法暂停导致2秒的延迟。所有标签都会更新其最终值,但不会每2秒更新一次。当我调试时,我可以看到值每2秒增加一个。此代码在按钮onClick事件中编写
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();
}
}
推荐答案
到使用Timer解决你的任务需要用你的代码实现 TimerTask
并使用 Timer#scheduleAtFixedRate
方法重复运行该代码:
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);
另请注意,调用任何UI操作必须在Swing UI线程(或FX UI线程,如果您)上完成正在使用JavaFX):
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);
}
如果是JavaFX,您需要在FX UI线程上更新FX控件而不是摆动一个。要实现这一点,请使用 javafx.application.Platform#runLater
方法而不是 SwingUtilities
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
这篇关于如何在java fx中每2秒更新一次标签框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!