JavaFX 启动另一个应用程序

2022-09-03 04:53:00

我一直在用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()

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

@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的更新方法中运行这个新阶段。

欢迎提出任何建议。谢谢。


答案 1

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

如果要有一个新窗口 -- 请创建一个 .Stage

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

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

答案 2

我在Main类中做了另一个JFX类的构造函数,然后调用了该方法。它工作得很好。你可以把它放在main()或其他方法中。它可能与 launch(args) 方法执行的操作相同AnotherClass ac = new AnotherClass();ac.start(new Stage);