Nurox Nurox - 1 year ago 692
Java Question

JavaFX call a controller method from the main class

I have a little problem with my JavaFX Application, I want to call a method in a controller from the main Class but it does not work.

I tried this Accessing FXML controller class
and this How do I access a UI element from another controller class in JavaFX?

But it does not work.

So, in my Application I have a main window and from there I can open a second window, when I close the second window I want to call a method in the main controller for updating some elements..

My main class have this two Windows:

public void start(Stage primaryStage) throws IOException {
this.primaryStage = primaryStage;

public void mainWindow() {
try {
FXMLLoader loader = new FXMLLoader(MainApp.class.getResource("/App.fxml"));
Parent root = loader.load();
AppController appController = loader.getController();
Scene scene = new Scene(root);
} catch (IOException e) {

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();
stage.setScene(new Scene(root));;
stage.setOnCloseRequest(event -> {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Schließen Bestätigung");
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


} catch (Exception e) {

Is there a way to call the method there?

thanks 4 reading

Answer Source

Your secondWindow() method is never called.

When you do call it, just pass the reference to the appController, which you already retrieved from the FXML via AppController appController = loader.getController();, to the method which creates the new window.

Change the signature of:



secondWindow(final AppController appController)