所以我試圖從循環非常頻繁地更新文本區域// This code makes the UI freez and the textArea don't get updatedfor(int i = 0; i < 10000; i++){ staticTextArea.appendText("dada \n");}我還嘗試實現一個BlockingQueue來創建更新TextArea的任務,這解決了UI的凍結問題,但TextArea在大約一百個循環后停止更新,但同時System.out.print(“dada \n”);按預期工作。 private static final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100); private static Thread mainWorker; private static void updateTextArea() { for(int i = 0 ; i < 10000; i++) { addJob(() -> { staticTextArea.appendText("dada \n"); System.out.print("dada \n"); }); } } private static void addJob(Runnable t) { if (mainWorker == null) { mainWorker = new Thread(() -> { while (true) { try { queue.take().run(); } catch (InterruptedException e) { e.printStackTrace(); } } }); mainWorker.start(); } queue.add(t); }
1 回答

瀟瀟雨雨
TA貢獻1833條經驗 獲得超4個贊
發生這種情況是因為你阻止了 UI 線程。
JavaFX 提供了該類,該類公開了該方法。該方法可用于在 JavaFX 應用程序線程(與 UI 線程不同)上運行長時間運行的任務。PlatformrunLater
final Runnable appendTextRunnable =
() -> {
for (int i = 0; i < 10000; i++) {
staticTextArea.appendText("dada \n");
}
};
Platform.runLater(appendTextRunnable);
添加回答
舉報
0/150
提交
取消