简体   繁体   English

Javafx:从另一个Java类打开新的FXML

[英]Javafx: Open a new FXML from another Java Class

I have a JavaFx application with following files: 我有一个包含以下文件的JavaFx应用程序:

  1. MainApp.java - Java class responsible for handling the application MainApp.java-负责处理应用程序的Java类
  2. Controller.java - Corresponding controller file Controller.java-对应的控制器文件
  3. Design.fxml - FXML file for the application which is loaded via MainApp.java and controlled by Controller.java Design.fxml-通过MainApp.java加载并由Controller.java控制的应用程序的FXML文件

Now, let's say I have another class file as Compute.java which has a method (say doSomething()). 现在,假设我有另一个类文件Compute.java,它具有一个方法(例如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"). 当该方法终止时,我希望在原始FXML文件的顶部打开一个内置的Alert框或一个自定义FXML文件(例如,状态为“工作已完成”的框)。

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). 请为此提出一个整洁的解决方案(这不涉及将Compute.java的逻辑移动到任何其他文件或Controller.java。此外,我希望保持Compute.java的JavaFx代码清洁)。

Suggestion: 建议:

Since the main primary stage (and scene) held in MainApp, 由于主要的主要阶段(和场景)在MainApp中举行,
you may inject this class into Compute 您可以将此类注入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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM