我的主线程启动javafx.application.Application
,它在作业完成后终止。当我尝试再次启动同一个 JavaFX 应用程序时,我总是收到 IllegalStateException:应用程序启动不得调用多次。
简单的演示示例:
public class MainApp {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
FXApp.setCounter(i);
System.out.println("launching i="+i);
FXApp.launch(FXApp.class, args);
}
}
}
public class FXApp extends Application {
private static int counter;
public static void setCounter(int counter) {
FXApp.counter = counter;
}
@Override
public void start(Stage primaryStage) throws Exception {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
Platform.exit();
}
}
@Override
public void stop() throws Exception {
super.stop();
System.out.println("stopping counter="+counter);
}
}
控制台输出
launching i=0
stopping counter=0
launching i=1
Exception in thread "main" java.lang.IllegalStateException: Application launch must not be called more than once
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:162)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:143)
at javafx.application.Application.launch(Application.java:191)
at ...MainApp.main(MainApp.java:9)
我该如何解决这个问题?
最佳答案
Application
类代表整个正在运行的应用程序。名为 launch()
的静态方法用于启动应用程序。由于根据定义,您只能在应用程序的生命周期内启动任何给定的应用程序一次,因此在应用程序的生命周期内多次调用 launch
是非法的,这样做会引发异常,如clearly and explicitly detailed in the documentation .
调用 launch()
创建代表正在运行的应用程序的 Application
子类的实例,启动 JavaFX 工具包,并调用 start()
在应用程序实例上。因此,start()
方法实际上是应用程序的入口点。请注意,start()
是在 FX 应用程序线程上调用的(因此此处不能有长时间运行或阻塞的代码)。再次强调,所有细节都在 documentation 中仔细阐明。 .
您还没有说明您实际想要做什么,并且由于您使用方法和类的方式与其预期用途完全相反,因此几乎不可能猜测您的意思问题。然而,等效的功能可以通过类似的东西来实现
public class FXApp extends Application {
@Override
public void start(Stage primaryStage) {
Thread pausingAndIteratingThread = new Thread(() -> {
for (int i = 0 ; i < 10 ; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException exc) {
exc.printStackTrace();
} finally {
final int counter = i ;
Platform.runLater(() -> endIteration(counter));
}
}
};
pausingAndIterartingThread.start();
}
private void endIteration(int counter) {
System.out.println("stopping: counter="+counter);
}
}
然后
public class MainApp {
public static void main(String[] args) {
Application.launch(FXApp.class, args);
}
}
关于java - 如何重新运行JavaFX应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37031932/