从我的MainProject(Java 8)中,我启动了一个JavaFX 8类。
public void startFX() {
if (isRestartPrintModul() == true) {
fxMain.init();
} else {
setRestartPrintModul(true);
fxMain.main(new String[] {"ohne"});
}
}
这是我的FXMain:
package quality;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
/**
*
* @author pu_laib
*/
public class FXMain extends Application {
private static Stage primaryStage;
@Override
public void init() {
Platform.setImplicitExit(false);
if (getPrimaryStage() != null) {
getPrimaryStage().show();
} else {
}
}
@Override
public void start(Stage primaryStage) {
setPrimaryStage(primaryStage);
// -> Applicationerror: getPrimaryStage().initModality(Modality.NONE);
// -> Applicationerror: getPrimaryStage().initModality(Modality.APPLICATION_MODAL);
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction((ActionEvent event) -> {
System.out.println("Hello World!");
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
getPrimaryStage().setTitle("Hello World!");
getPrimaryStage().setScene(scene);
getPrimaryStage().show();
this.primaryStage.setOnCloseRequest((WindowEvent event) -> {
Platform.exit();
});
}
public static void main(String[] args) {
launch(args);
}
public Stage getPrimaryStage() {
return primaryStage;
}
public void setPrimaryStage(Stage primaryStage) {
this.primaryStage = primaryStage;
}
}
虽然在我看来它已经关闭,但不可能再次从我的MainProject调用打印模块。
一旦PrintModul模块完成,launch就不记得以前运行过了,对吧?
怎么了?
谢谢。
Application::launch(args)方法的文档说明:
不能多次调用它,否则将引发异常。
所以:
- 只需调用一次启动即可
- 调用
Platform.setImplicitExit(false)
,以便即使所有阶段都关闭,JavaFX运行时也将继续运行 - 一旦JavaFX应用程序完成了它的工作,就不要调用
Platform.exit()
,而是让JavaFX平台继续运行,即使你没有积极使用它 - 与其再次尝试启动应用程序,不如调用应用程序的
start()
方法(或您在应用程序上提供的接受要传递的参数的其他公共方法)来"运行"应用程序一秒钟或多次(如果需要,可以实例化一个新阶段以传递到启动方法) - 一旦所有的工作都完成了,那么就调用
Platform.exit()
来干净地关闭JavaFX系统
您的另一个选择是启动一个新流程,而不是在与MainProject相同的流程中运行JavaFX应用程序,但总的来说,我建议您采用上述方法,而不是创建新流程。