JavaFX启动另一个应用程序

lin*_*boy 11 java multithreading javafx-2

我一直在用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我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 */
}
Run Code Online (Sandbox Code Playgroud)

它在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//
    }
}
Run Code Online (Sandbox Code Playgroud)

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

欢迎任何建议.谢谢.

Ser*_*nev 25

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

如果你想有一个新窗口 - 创建一个Stage.

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

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

  • 你是新的 anotherApp().start(new Stage()); 的救星@SergeyGrinev 我也一直在为一个类似的问题自责,你的建议有所帮助。谢谢! (2认同)