JavaFX启动另一个应用程序

我一直在用JavaFx粉碎我的脑袋……

这适用于没有运行应用程序的实例的情况:

public class Runner { public static void main(String[] args) { anotherApp app = new anotherApp(); new Thread(app).start(); } } public class anotherApp extends Application implements Runnable { @Override public void start(Stage stage) { } @Override public void run(){ launch(); } } 

但是如果我另一个应用程序中执行new Thread(app).start() 我会得到一个exception,说明我不能进行两次启动。

此外,我的方法由另一个应用程序上的观察者调用,如下所示:

 @Override public void update(Observable o, Object arg) { // new anotherApp().start(new Stage()); /* Not on FX application thread; exception */ // new Thread(new anotherApp()).start(); /* java.lang.IllegalStateException: Application launch must not be called more than once */ } 

它位于JavaFX类中,例如:

 public class Runner extends Applications implements Observer { public static void main(String[] args) { launch(args); } @Override public void start(Stage stage){ //...code...// } //...methods..// //...methods..// @Override public void update(Observable o, Object arg) { //the code posted above// } } 

我尝试将ObjectProperties与侦听器一起使用,但它不起作用。 我需要以某种方式从java.util.observer的update方法中运行这个新阶段。

欢迎任何建议。 谢谢。

应用程序不仅仅是一个窗口 – 它是一个Process 。 因此,每个VM只允许一个Application#launch()

如果您想要一个新窗口 – 创建一个Stage

如果你真的想重用anotherApp类,只需将它包装在Platform.runLater()

 @Override public void update(Observable o, Object arg) { Platform.runLater(new Runnable() { public void run() { new anotherApp().start(new Stage()); } }); } 

我在Main类中做了另一个JFX类的构造函数AnotherClass ac = new AnotherClass(); 然后调用方法ac.start(new Stage); 。 它对我很好。 你可以把它放在main()或另一种方法中。 它与启动(args)方法的作用可能相同

由于一个使用的警告,想要提供第二个答案
Application.start(阶段阶段)。

在init方法返回后调用start方法

如果您的JavaFX应用程序具有覆盖Application.init(),则该代码永远不会执行。 您在第二个应用程序main方法中没有任何代码。

启动第二个JavaFX应用程序的另一种方法是使用ProcessBuilder API启动新进程。

  final String javaHome = System.getProperty("java.home"); final String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; final String classpath = System.getProperty("java.class.path"); final Class klass = TestApplication2.class; final String className = klass.getCanonicalName(); final ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); final Button button = new Button("Launch"); button.setOnAction(event -> { try { Process process = builder.start(); } catch (IOException e) { e.printStackTrace(); } });