如何在JavaFX GUI中不断更新少量文本字段?

时间:2016-11-28 22:17:04

标签: java javafx

在后台线程中保持少量文本字段不断更新的最佳方法是什么?我正在记录一些来自quadrotor fly的变量,我将它保存在DronCoordinator类中。每次更改(100毫秒)我都想在GUI文本字段中更新它们的值。我尝试过使用Task类的updateMessage()方法,但是这样我只能继续更新1个文本字段。我需要添加3或4个变量来保持更新。它运行良好,但只有1个变量可以更新。

public class ApplicationControler implements Initializable {


@FXML
private Canvas artHorizon;

@FXML
public TextField pitchValue;

@FXML
private TextField rollValue;

@FXML
private TextField yawValue;

@FXML
private TextField thrustValue;

@FXML
private Button start;



private Service<Void> backgroundThread;

@Override
public void initialize(URL location, ResourceBundle resources) {

}

@FXML
private void applicationStart(ActionEvent event) {

    backgroundThread = new Service<Void>() {


        @Override
        protected Task<Void> createTask() {

            return new Task<Void>() {


                @Override
                protected Void call() throws Exception {


        //This is the place where class which uptades variables starts

                        updateMessage(DronCoordinator.pitch);


                    return null;
                }

            };

        }
    };

    backgroundThread.setOnSucceeded(new EventHandler<WorkerStateEvent>() {

        @Override
        public void handle(WorkerStateEvent event) {

            pitchValue.textProperty().unbind();


        }
    });



    pitchValue.textProperty().bind(backgroundThread.messageProperty());

    backgroundThread.restart();

}

}

2 个答案:

答案 0 :(得分:0)

您可以在javafx中将此方法添加到文本框中:

textbox.rawText() ->  which keeps on updating your textbox whatever is currently in it.

答案 1 :(得分:0)

创建一个可以从任务传递给updateMessage的模型对象。这背后的想法是在一个对象中收集各种值,然后使用所有值更新GUI,而不是分别更新每个值。该模型看起来与此类似:

public class DroneModel {
  private double pitch;
  private double roll;
  private double yaw;
  private double thrust;

  public double getPitch() {
    return pitch;
  }

  public void setPitch(double pitch) {
    this.pitch = pitch;
  }

  public double getRoll() {
    return roll;
  }

  public void setRoll(double roll) {
    this.roll = roll;
  }

  public double getYaw() {
    return yaw;
  }

  public void setYaw(double yaw) {
    this.yaw = yaw;
  }

  public double getThrust() {
    return thrust;
  }

  public void setThrust(double thrust) {
    this.thrust = thrust;
  }
}

然后您的更新方法如下所示:

public void updateMessage(DroneModel model) {
  pitchValue.setText(String.valueOf(model.getPitch()));
  rollValue.setText(String.valueOf(model.getRoll()));
  yawValue.setText(String.valueOf(model.getYaw()));
  thrustValue.setText(String.valueOf(model.getThrust()));
}

关键部分是如何调用此更新方法,您必须使用runLater,如@RahulSingh所述:

Platform.runLater(() -> updateMessage(droneModel));