1

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).

Dilpreet Kaur
  • 465
  • 2
  • 4
  • 12

1 Answers1

0

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();
}
Uluk Biy
  • 48,655
  • 13
  • 146
  • 153
  • I attempted this, but I get `Not on FX application thread` error upon invoking the alertbox from MainApp.java. – Dilpreet Kaur Jun 09 '15 at 05:10
  • Does MainJava extend javafx.application.Application? – Uluk Biy Jun 09 '15 at 05:30
  • Yea, `MainApp` is running otherwise. Only when I try to initiate the alertbox, it shows this error. Also, there's another thing: I didn't instantiate the `Compute` object in `MainApp`, but I have another class, say `Compute2`, which has a static field of `Compute`, so I call `Compute2.compute.setMainApp(this)` in `MainApp`. – Dilpreet Kaur Jun 09 '15 at 05:47
  • @DilpreetKaur, the static variable shouldn't be a problem. I am trying to guess but can't find the reason. Are you using Threads? Anyway try to wrap showAlert() method's content into Platform.runLater(), as a last option. Otherwise it is better to determine the resion of that exception. – Uluk Biy Jun 09 '15 at 06:04
  • Thanks! I'm not using threads. For now, `Platform.runLater()` has solved the problem. – Dilpreet Kaur Jun 09 '15 at 08:20