Javafx: Open a new FXML from another Java Class

2019-08-14 15:04发布

问题:

I have a JavaFx application with following files:

  1. MainApp.java - Java class responsible for handling the application
  2. Controller.java - Corresponding controller file
  3. Design.fxml - FXML file for the application which is loaded via MainApp.java and controlled by Controller.java

Now, let's say I have another class file as Compute.java which has a method (say doSomething()). When this method terminates, I wish to open a built-in Alert box or a custom FXML file on top of the original FXML file (say, a box which states "Work Completed").

Please suggest a neat solution for this (which does not involve moving the logic of Compute.java to any other file or to the Controller.java. Also, I wish to keep the Compute.java clean of JavaFx code).

回答1:

Suggestion:

Since the main primary stage (and scene) held in MainApp,
you may inject this class into Compute

// in MainApp.java
Compute compute = new Compute();
compute.setMainApp(this);

After that you call

// in Compute.java
mainApp.showAlert(myTitle, myContent);

where

// in MainApp.java
public void showAlert(String myTitle, Node myContent) {
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle(myTitle);
    alert.setHeaderText(null);
    alert.getDialogPane.setContent(myContent);
    alert.showAndWait();
}

// or your custom stage
public void showAlert(String myTitle, Node myContent) {
    Stage dialogStage = new Stage();
    dialogStage.initModality(Modality.WINDOW_MODAL);
    dialogStage.setScene(new Scene(new VBox(new Label(myTitle), myContent));
    dialogStage.show();
}