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

use*_*861 5 java swing javafx javafx-2

我正在尝试在应用程序GUI中模拟基本恒温器.

我想用新的温度值每2秒更新一个标签盒值.

例如,我的初始温度将显示为68度并更新为69,至70等,直到每2秒75次.

这是我用Java fx编写的一段代码. controlpanel是标签盒所在的te形式的对象.它仅将最终值更新为75.它不会每2秒更新一次.我写了一个方法暂停,导致2秒的延迟.所有标签都会更新其最终值,但不会每2秒更新一次.当我调试时,我可以看到值每2秒增加一个.此代码是在按钮onClick事件中编写的

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();
    }
 }  
Run Code Online (Sandbox Code Playgroud)

Ser*_*nev 13

要使用Timer解决您的任务,您需要TimerTask使用代码实现并使用Timer#scheduleAtFixedRate方法重复运行该代码:

Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            System.out.print("I would be called every 2 seconds");
        }
    }, 0, 2000);
Run Code Online (Sandbox Code Playgroud)

另请注意,调用任何UI操作必须在Swing UI线程(或FX UI线程,如果您使用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);
}
Run Code Online (Sandbox Code Playgroud)

对于JavaFX,您需要更新"FX UI线程"而不是Swing 1的FX控件.要实现那种使用javafx.application.Platform#runLater方法而不是SwingUtilities


jew*_*sea 10

这是一个使用JavaFX动画时间轴而不是Timer的替代解决方案.

我喜欢这个解决方案,因为动画框架确保JavaFX应用程序线程上发生的一切,所以您不必担心线程问题.

温度探针

import javafx.animation.*;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.util.Random;

public class ThermostatApp extends Application {
  @Override public void start(final Stage stage) throws Exception {
    final Thermostat       thermostat       = new Thermostat();
    final TemperatureLabel temperatureLabel = new TemperatureLabel(thermostat);

    VBox layout = new VBox(10);
    layout.getChildren().addAll(temperatureLabel);
    layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 20; -fx-font-size: 20;");

    stage.setScene(new Scene(layout));
    stage.show();
  }

  public static void main(String[] args) throws Exception {
    launch(args);
  }
}

class TemperatureLabel extends Label {
  public TemperatureLabel(final Thermostat thermostat) {
    textProperty().bind(
      Bindings.format(
        "%3d \u00B0F",
        thermostat.temperatureProperty()
      )
    );
  }
}

class Thermostat {
  private static final Duration PROBE_FREQUENCY = Duration.seconds(2);

  private final ReadOnlyIntegerWrapper temperature;
  private final TemperatureProbe       probe;
  private final Timeline               timeline;

  public ReadOnlyIntegerProperty temperatureProperty() {
    return temperature.getReadOnlyProperty();
  }

  public Thermostat() {
    probe       = new TemperatureProbe();
    temperature = new ReadOnlyIntegerWrapper(probe.readTemperature());

    timeline = new Timeline(
        new KeyFrame(
          Duration.ZERO,
          new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent actionEvent) {
              temperature.set(probe.readTemperature());
            }
          }
        ),
        new KeyFrame(
          PROBE_FREQUENCY
        )
    );
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.play();
  }
}

class TemperatureProbe {
  private static final Random random = new Random();

  public int readTemperature() {
    return 72 + random.nextInt(6);
  }
}
Run Code Online (Sandbox Code Playgroud)

该解决方案基于以下的倒数计时器解决方案:JavaFX:如何绑定两个值?

  • 是的,动画计时器确实在 JavaFX 应用程序上运行,并且它可以以某种方式来回答这个问题。使用时间线更直接,因为它是一个更高级别的构造,完全满足问题的要求,以对时间线使用的 KeyFrame 结构设置直观的方式每 2 秒调用一次 UI 更新。如果您想要执行更新的时间间隔可能不断变化的游戏循环或物理模型,AnimationTimer 是合适的。 (2认同)