Oscar.Aldaz
Oscar.Aldaz

Reputation: 57

Call a method of a controller from another controller JavaFX

I have a problem, i'm doing a program that simulates the FCFS algorithm. I'm working with threads. The thing is that when I press T the program needs to interrupt the thread and show a window(stage) with a table, when I close the stage i need to start again the thread, so my idea is that from the second controller call the function of the other controller and then close the stage Here is where i call the second stage:

case T:
            banderaPause=true;
            th.interrupt();
            Stage stTableView = new Stage();
            FXMLLoader loader = new FXMLLoader();
            Pane root = null;
            try {
                root = loader.load(getClass().getResource("showTable.fxml").openStream());
                showTableController stController = (showTableController)loader.getController();
                stController.init(arreglo);
                stTableView.setTitle("Programa 4");
                stTableView.setScene(new Scene(root, 950, 375));
                stTableView.setX(2.00);
                stTableView.setY(300.00);
                stTableView.show();
                stTableView.setOnCloseRequest(new EventHandler<WindowEvent>() {
                    @Override
                    public void handle(WindowEvent event) {
                        System.out.println("ya cerre");
                    }
                });

            } catch (IOException e1) {
                e1.printStackTrace();
            }
            break;

And here is where i tried to call the method from the second controller:

case C:
            try {
                FXMLLoader loader = new FXMLLoader();
                loader.setLocation(getClass().getResource("second.fxml"));
                Parent  root = loader.load();
                Controller n = loader.getController();
                n.Continua();
                Stage stage = (Stage) closeButton.getScene().getWindow();
                stage.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            break;

But the stage just close and the method was never called

Upvotes: 0

Views: 1104

Answers (1)

fabian
fabian

Reputation: 82521

From the javadoc for onCloseRequested (emphasis mine):

Called when there is an external request to close this Window.

So the handler is not executed, if you call close yourself.

For Stages that are not the primary stage there is an option to wait for the window to be closed, however: Stage.showAndWait, so you could use this instead of registering an event handler:

stTableView.showAndWait();

// Print to console after stage is closed
System.out.println("ya cerre");

Upvotes: 1

Related Questions