據說我有一個擴展的應用程式類可以從另一個類啟動
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();
}
.
.
.
我想從另一個類創建同一階段的多個實體,所以我可能會創建一個階段串列
private static List<Stage> stages;
@Override
public void start(Stage primaryStage) throws Exception {
for (Stage st : stages) {
st.show();
}
}
.
.
.
所以我定義了一個靜態方法來從另一個類實體化舞臺
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;
}
}
但是,當我嘗試啟動課程并創建舞臺時,
public class MainClass {
public static void main (String[] args) {
BasicApp app = getInstance();
app.createStage("Test");
}
}
它拋出了一個例外,指出不能在 FX 應用程式執行緒之外創建舞臺。
java.lang.IllegalStateException: Not on FX application thread;
應用程式實體沒有問題,但是,如何在不出現此錯誤的情況下實作創建同一階段的實體?
uj5u.com熱心網友回復:
您可以使用Platform.runLater()在 FX 應用程式執行緒上執行代碼。
public class MainClass {
public static void main (String[] args) {
BasicApp app = getInstance();
Platform.runLater(() -> createStage("Test"));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/310820.html
上一篇:Spring-bootmongodb-如何將MongoRepository保存回應轉換為自定義類并作為JSON回傳
