我希望实现一个线程,每隔几秒运行一次 QueueTabPageController
中的 displayQueue
方法,以便在 JavaFX GUI 上自动更新 TableView 。目前它是通过按下 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
最佳答案
可能是这样的:
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(真);将确保线程不会阻止 JVM 在所有其他线程完成时终止。可能有更好的方法来处理线程关闭...
关于JavaFX 刷新 TableView 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29883781/