如何重新运行JavaFX App

时间:2016-05-04 15:21:41

标签: java javafx javafx-2

我的主线程启动javafx.application.Application,它在作业完成后终止它的文件。当我尝试再次启动相同的JavaFX应用程序时,我总是收到IllegalStateException: Application launch must not be called more than once.

简单的示范性例子:

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)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

Application类表示整个正在运行的应用程序。名为launch()的静态方法用于启动应用程序。根据定义,您可以在应用程序的生命周期中仅启动任何给定的应用程序一次,在应用程序的生命周期中多次调用launch是违法的,这样做会抛出异常,因为clearly and explicitly detailed in the documentation

调用launch()创建代表正在运行的应用程序的Application子类的实例,启动JavaFX工具包,并在应用程序实例上调用start()。因此start()方法实际上是应用程序的入口点。请注意,在FX应用程序线程上调用start()(因此您不能在此处使用长时间运行或阻塞代码)。同样,所有细节都在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);
    }
}