如何在 JavaFX 中从另一个 class 动态创建舞台
How to dynamically create stage from another class in JavaFX
我想我有一个扩展应用程序 class 可以从另一个 class
启动
public class BasicApp extends Application {
public static CountDownLatch instanceLatch = new CountDownLatch(1);
public static BasicApp instance;
public synchronized static BasicApp getInstance() {
if(instance == null) {
try {
new Thread(() -> Application.launch(BasicApp.class)).start();
instanceLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return instance;
}
public BasicApp () {
instance = this;
instanceLatch.countDown();
}
.
.
.
而且我想从另一个 class 创建同一阶段的多个实例,所以我可能会创建一个阶段列表
private static List<Stage> stages;
@Override
public void start(Stage primaryStage) throws Exception {
for (Stage st : stages) {
st.show();
}
}
.
.
.
所以我定义了一个静态方法来从另一个class
实例化舞台
public static Stage createStage(String data) {
Stage stage = new Stage();
Scene scene = new Scene(new Label(data));
stage.setScene(scene);
stages.add(stage);
return stage;
}
}
但是,当我尝试启动 class 并创建舞台时,
public class MainClass {
public static void main (String[] args) {
BasicApp app = getInstance();
app.createStage("Test");
}
}
它引发了一个异常,指出无法在 FX 应用程序线程之外创建舞台。
java.lang.IllegalStateException: Not on FX application thread;
应用实例没有问题,但是,
如何在不出现此错误的情况下创建同一阶段的实例?
您可以使用 Platform.runLater()
在 FX 应用程序线程上执行代码。
public class MainClass {
public static void main (String[] args) {
BasicApp app = getInstance();
Platform.runLater(() -> createStage("Test"));
}
}
我想我有一个扩展应用程序 class 可以从另一个 class
启动public class BasicApp extends Application {
public static CountDownLatch instanceLatch = new CountDownLatch(1);
public static BasicApp instance;
public synchronized static BasicApp getInstance() {
if(instance == null) {
try {
new Thread(() -> Application.launch(BasicApp.class)).start();
instanceLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return instance;
}
public BasicApp () {
instance = this;
instanceLatch.countDown();
}
.
.
.
而且我想从另一个 class 创建同一阶段的多个实例,所以我可能会创建一个阶段列表
private static List<Stage> stages;
@Override
public void start(Stage primaryStage) throws Exception {
for (Stage st : stages) {
st.show();
}
}
.
.
.
所以我定义了一个静态方法来从另一个class
实例化舞台 public static Stage createStage(String data) {
Stage stage = new Stage();
Scene scene = new Scene(new Label(data));
stage.setScene(scene);
stages.add(stage);
return stage;
}
}
但是,当我尝试启动 class 并创建舞台时,
public class MainClass {
public static void main (String[] args) {
BasicApp app = getInstance();
app.createStage("Test");
}
}
它引发了一个异常,指出无法在 FX 应用程序线程之外创建舞台。
java.lang.IllegalStateException: Not on FX application thread;
应用实例没有问题,但是, 如何在不出现此错误的情况下创建同一阶段的实例?
您可以使用 Platform.runLater()
在 FX 应用程序线程上执行代码。
public class MainClass {
public static void main (String[] args) {
BasicApp app = getInstance();
Platform.runLater(() -> createStage("Test"));
}
}