我试过阅读java文档并做了很多研究,但都没有。基本上,当我更改场景时,我想要取消定时器。 timer的代码。省略了我创建定时器的部分。初始化时,我将调用timer timerUpdateLiveInfo():
private void timerUpdateLiveInfo() {
t1.schedule(tt1, 0,5000);
}
TimerTask tt1=new TimerTask() {
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
PendingOrders.setText(String.valueOf(orderDB.getNumOfOrder()));
String record = orderDB.getTopCanteens();
//System.out.println(orderDB.getTopCanteens());
String[] fields = record.split(";"); // attributes separated by ;
String canteenTop=fields[0];
String canteenTop2=fields[1];
String canteenTop3=fields[2];
MostPopularLabel1.setText(canteenTop);
MostPopularLabel2.setText(canteenTop2);
MostPopularLabel3.setText(canteenTop3);
}
});
}
};
当我尝试取消“本地”时,从按钮开始工作。
@FXML
void handleTestingButton(ActionEvent event) {
cancelTimer();
}
和
public void cancelTimer() {
tt1.cancel();
t1.cancel();
System.out.println("Cancelled");
t2.cancel();
}
但是,当我尝试在更改场景后使用另一个fxml进行调用时,计时器仍会继续运行:
public void handleReturnToUser(ActionEvent event) throws IOException {
WorkerHomeController workerHome= new WorkerHomeController();
workerHome.cancelTimer();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/ooppFinalProject/view/HomePage1.fxml"));
myScene = (Scene) ((Node) event.getSource()).getScene();
Stage stage = (Stage) (myScene).getWindow();
Parent nextView = loader.load();
workerHome.cancelTimer();
stage.setScene(new Scene(nextView));
stage.setTitle("Home Page");
stage.show();
}
请帮忙。非常感谢你!
更新:
public void handleReturnToUser(ActionEvent event) throws IOException{
//workerHome.cancelTimer();
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/ooppFinalProject/view/HomePage1.fxml"));
myScene = (Scene) ((Node) event.getSource()).getScene();
Stage stage = (Stage) (myScene).getWindow();
Parent nextView = loader.load();
//workerHome.cancelTimer();
WorkerHomeController workerHome=loader.getController();
workerHome.cancelTimer();
stage.setScene(new Scene(nextView));
stage.setTitle("Home Page");
stage.show();
}
和Stack Trace:
Caused by: java.lang.ClassCastException: ooppFinalProject.controller.HomePage1Controller cannot be cast to ooppFinalProject.controller.WorkerHomeController
at ooppFinalProject.controller.WorkerSideTabController.handleReturnToUser(WorkerSideTabController.java:91)
... 62 more
答案 0 :(得分:1)
试试这个:
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/ooppFinalProject/view/HomePage1.fxml"));
myScene = (Scene) ((Node) event.getSource()).getScene();
Stage stage = (Stage) (myScene).getWindow();
Parent nextView = loader.load();
WorkerHomeController workerHome=loader.getController();
workerHome.cancelTimer();
说明:您需要在workerHome.cancelTimer();
上调用WorkerHomeController
loader.load();
实际上是loader.getController();
时的控制器创建者,然后通过{{1}}