[英]JavaFX launch another application
我一直在用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的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類AnotherClass ac = new AnotherClass();
做了另一個JFX類的構造函數AnotherClass ac = new AnotherClass();
然后調用方法ac.start(new Stage);
。 它對我很好。 U可以將其放在main()或其他方法中。 它的功能可能與launch(args)方法相同
由於使用一個警告,希望提供第二個答案
Application.start(階段)。
返回init方法后調用start方法
如果您的JavaFX應用程序具有Override 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<TestApplication2> 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();
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.