JavaFX 刷新 TableView 线程

4

我希望实现一个线程,每隔几秒钟运行QueueTabPageController中的displayQueue方法,以便在JavaFX GUI上自动更新表视图。目前,GUI中通过手动按下刷新按钮进行更新,但这并不理想。我尝试过一些在此处的示例使用各种方法,但似乎无法正确运行。顺便说一句,我是新手对于线程不太熟悉。任何帮助将不胜感激。

public class QueueTabPageController implements Initializable {

  @FXML
  private TableView<Patient> tableView;

  @FXML
  private TableColumn<Patient, String> firstNameColumn;

  @FXML
  private TableColumn<Patient, String> lastNameColumn;

  @FXML
  private TableColumn<Patient, String> timeEnteredColumn;

  @FXML
  private TableColumn<Patient, String> triageAssessmentColumn;

  @FXML
  private QueueTabPageController queueTabPageController;

  private ObservableList<Patient> tableData;

  @Override
  public void initialize(URL arg0, ResourceBundle arg1) {

    assert tableView != null : "fx:id=\"tableView\" was not injected: check your FXML file 'FXMLQueueTabPage.fxml'";

    firstNameColumn.setCellValueFactory(new PropertyValueFactory<Patient, String>("firstName"));
    lastNameColumn.setCellValueFactory(new PropertyValueFactory<Patient, String>("lastName"));
    timeEnteredColumn.setCellValueFactory(new PropertyValueFactory<Patient, String>("time"));
    triageAssessmentColumn.setCellValueFactory(new PropertyValueFactory<Patient, String>("triage"));

    // display the current queue to screen when opening page each time
    displayQueue(Queue.queue);

  }

  /**
   * @param event
   * @throws IOException
   */
  @FXML
  private void btnRefreshQueueClick(ActionEvent event) throws IOException {
    displayQueue(Queue.queue);
  }

  /**
   * @param queue
   */
  public void displayQueue(LinkedList<Patient> queue) {
    tableData = FXCollections.observableArrayList(queue);
    tableView.setItems(tableData);
    tableView.getColumns().get(0).setVisible(false);
    tableView.getColumns().get(0).setVisible(true);
  }

}

感谢您,K
1个回答

1

可能是这样的:

    Thread t = new Thread(() -> {
        while (true) {
            Thread.sleep(5000); // sleep 5 secs
            Platform.runLater(() -> {   // Ensure data is updated on JavaFX thread 
                displayQueue(Queue.queue);
            });
        }
    }); 
    t.setDaemon(true);
    t.start();

这将启动一个线程,每5秒调用displayQueue(Queue.queue)。由于displayQueue(...)调用tableView.setItems(...),因此必须在JavaFX应用程序线程上调用它,因此需要使用Platform.runLater()。
t.setDaemon(true)将确保该线程不会阻止JVM在所有其他线程完成时终止。可能有更好的方法来处理线程关闭...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接