我的JavaFX应用程序有点问题,我想从主类中调用控制器中的方法,但它不起作用。
我试过这个Accessing FXML controller class 这个How do I access a UI element from another controller class in JavaFX?
但它不起作用。
所以,在我的应用程序中我有一个主窗口,从那里我可以打开第二个窗口,当我关闭第二个窗口时,我想在主控制器中调用一个方法来更新一些元素..
我的主要课程有两个Windows:
@Override
public void start(Stage primaryStage) throws IOException {
this.primaryStage = primaryStage;
mainWindow();
public void mainWindow() {
try {
FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("/App.fxml"));
Parent root = loader.load();
AppController appController = loader.getController();
appController.setMain(this);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void secondWindow() throws IOException {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("SecondWindow.fxml"));
Parent root = loader.load();
Stage stage = new Stage();
SecondWindowController secondWindowController = loader.getController();
secondWindowController.setStage(stage);
stage.initOwner(primaryStage);
stage.initModality(Modality.WINDOW_MODAL);
stage.setScene(new Scene(root));
stage.show();
stage.setOnCloseRequest(event -> {
event.consume();
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setHeaderText("close?");
alert.initOwner( stage);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
// Here I want to call the method to update in the AppController
stage.close();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
有没有办法在那里调用方法?
答案 0 :(得分:3)
永远不会调用您的secondWindow()
方法。
当您调用它时,只需将您已通过AppController appController = loader.getController();
从FXML检索到的appController传递给创建新窗口的方法。
更改签名:
secondWindow()
到:
secondWindow(final AppController appController)