我需要以下方面的帮助:我正在javafx中实现一个应用程序,该应用程序是通过单击按钮调用的。问题是当我关闭应用程序时,我无法再次调用它。我读过你不能多次调用Application.launch()方法。但我在服务类上发现了一些东西。文档页面中的示例不是很清楚。有人知道如何做到这一点吗?谢谢。
http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
我的代码:
private void jButton1ActionPerformed (java.awt.event.ActionEvent evt) {
WebMap n1 = new WebMap () / / application in javafx
n1.Lunch ();
}
WebMap 类://javafx 应用程序
public void Lunch () {
Application.launch ();
}
在同一进程中多次启动 JavaFX 应用程序,因此不要尝试这样做。
你需要找到一种替代机制来做你想做的任何事情。
如果要在 Swing 应用程序中嵌入 JavaFX 场景,则应在 Swing 中创建新的 JFXPanell,而不是在按下 Swing 按钮时创建新的 JavaFX 应用程序。
如果你打算有一个纯的JavaFX应用程序,那么就不需要一个启动JavaFX应用程序的摆动按钮,你可以使用JavaFX按钮代替,直接显示JavaFX场景。
在这种情况下,无需使用服务,服务用于在另一个线程上执行重复的后台任务,这与您正在尝试的内容无关。
如果您想集成 Swing 和 JavaFX 应用程序,请阅读面向 Swing 开发人员的 JavaFX。
作为com.bitplan.javafx开源项目的提交者,我可以向您指出我们已经使用了一段时间的解决方法:
https://github.com/BITPlan/com.bitplan.javafx/blob/master/src/main/java/com/bitplan/javafx/WaitableApp.java
WaitableApp.toolkitInit();
将初始化 JavaFX 环境。
https://github.com/BITPlan/com.bitplan.javafx/blob/master/src/main/java/com/bitplan/javafx/SampleApp.java
将演示一般如何使用 WaitableApp 基类的示例。您可能还想查看该项目的 Junit 测试用例。
等待应用程序
/**
* Waitable Application that does not need launch
*
* @author wf
*
*/
public abstract class WaitableApp extends Application {
protected Stage stage;
static boolean toolkitStarted;
/**
* allow startup without launch
*/
@SuppressWarnings("restriction")
public static void toolkitInit() {
if (!toolkitStarted) {
toolkitStarted = true;
// do not exit on close of last window
// https://stackoverflow.com/a/10217157/1497139
Platform.setImplicitExit(false);
/// https://stackoverflow.com/a/38883432/1497139
// http://www.programcreek.com/java-api-examples/index.php?api=com.sun.javafx.application.PlatformImpl
com.sun.javafx.application.PlatformImpl.startup(() -> {
});
}
}
@Override
public void start(Stage stage) {
this.stage = stage;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
/**
* wait for close
*
* @throws InterruptedException
*/
public void waitStatus(boolean open) {
int sleep = 1000 / 50; // human eye reaction time
try {
if (open)
while ((stage == null) || (!stage.isShowing())) {
Thread.sleep(sleep);
}
else
while (stage != null && stage.isShowing()) {
Thread.sleep(sleep);
}
} catch (InterruptedException e) {
ErrorHandler.handle(e);
}
}
public void waitOpen() {
waitStatus(true);
}
public void waitClose() {
waitStatus(false);
}
/**
* show me
*/
public void show() {
// ignore multiple calls
if (stage != null)
return;
Platform.runLater(() -> {
try {
this.start(new Stage());
} catch (Exception e) {
ErrorHandler.handle(e);
}
});
}
/**
* close this display
*/
public void close() {
Platform.runLater(() -> {
if (stage != null)
stage.close();
});
this.waitClose();
// allow reopening
stage = null;
}
}