Sla*_*ahh 3 java javafx initialization
当我在开发环境(Eclipse)中启动应用程序时,它会运行,但是,当我尝试将其导出到可运行的 .jar 文件时,它会出现以下错误:
Exception in thread "main" java.lang.ExceptionInInitializerError
at mallApp.MainTwo.<clinit>(MainTwo.java:24)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:59)
Caused by: java.lang.IllegalStateException: Toolkit not initialized
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:410)
at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:405)
at com.sun.javafx.application.PlatformImpl.setPlatformUserAgentStylesheet(PlatformImpl.java:695)
at com.sun.javafx.application.PlatformImpl.setDefaultPlatformUserAgentStylesheet(PlatformImpl.java:657)
at javafx.scene.control.Control.<clinit>(Control.java:99)
... 4 more
Run Code Online (Sandbox Code Playgroud)
问题是“由以下原因引起:java.lang.IllegalStateException:工具包未初始化”。
这里有很多关于类似问题的线程,但它们似乎都不完全相同,而且我尝试过的修复对我不起作用。我的类扩展了 Application,因此在 main 方法中具有 Application.launch(args) 。这应该初始化 Toolkit,但在导出到 .jar 时由于某种原因却没有初始化。
当我尝试以不同的方式添加 Toolkit 时,例如使用 JFXPanel 或Platform.startup(Runnable)
,它会给出相反的错误,提示 Toolkit 已初始化。
public class MainTwo extends Application {
...
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage arg0) throws Exception {
model = new Main2Model();
c = model.getCompanyList();
primaryStage = arg0;
primaryStage.setTitle("MallApp");
primaryStage.centerOnScreen();
showMainView();
}
Run Code Online (Sandbox Code Playgroud)
问题是我在声明静态 javafx-attributes 时已经初始化了它们。当我将字段的初始化移至启动方法时,问题已解决,JAR 变得可运行,如下所示:
而不是:
private static TextField total = new TextField();
private static ObservableList<String> items = FXCollections.observableArrayList();
public void start(Stage arg0) throws Exception {
model = new Main2Model();
c = model.getCompanyList();
primaryStage = arg0;
primaryStage.setTitle("MallApp");
primaryStage.centerOnScreen();
showMainView();
}
Run Code Online (Sandbox Code Playgroud)
我有:
private static TextField total;
private static ObservableList<String> items;
@Override
public void start(Stage arg0) throws Exception {
total = new TextField();
items = FXCollections.observableArrayList();
model = new Main2Model();
c = model.getCompanyList();
primaryStage = arg0;
primaryStage.setTitle("MallApp");
primaryStage.centerOnScreen();
showMainView();
}
Run Code Online (Sandbox Code Playgroud)