2016-11-28 37 views
-1

保持少量文本字段在後臺線程中不斷更新的最佳方式是什麼?我記錄了我在DronCoordinator類中保留的quadrotor fly的一些變量。每次他們改變(100毫秒)我想在GUI文本字段中更新它們的值。我已經嘗試從Task類的updateMessage()方法,但這樣我只能繼續更新1文本字段。我需要添加3個或4個更多的變量來保持更新。它工作良好,但只有1個變量才能更新。如何不斷更新JavaFX GUI中的幾個文本字段?

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(); 

} 

} 
+1

如果這適用於「pitchValue」文本字段,那麼對於其他3版本以相同的方式做什麼錯誤?另外,請更具體地說明你想要發生的事情。 – NonlinearFruit

+0

您是否想與GUI進行交互,同時在後臺運行任務?如果這是你想要的,你必須稍後使用Platform.run –

+0

@NonlinearFruit我不能這樣做,因爲backgroundThread.messageProperty()它只是一個字符串,所以當我將同一個messageProperty()與4個文本字段綁定時,所有字段將顯示相同的值。 – PawelW

回答

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)); 
0

您可以在JavaFX的這個方法添加到您的文本框:

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