使用JavaFX Platform.runLater并从不同的线程访问UI [英] Usage of JavaFX Platform.runLater and access to UI from a different thread
问题描述
我有一些关于 Platform.runLater
的问题。我有一个JavaFX Application类。在这个类中,我运行一个线程(线程从网络套接字读取数据)。
I have a few questions about Platform.runLater
. I have a JavaFX Application class. In this class I run a thread (The thread reads data from a network socket).
现在当我创建一个新的阶段
在线程内部,系统抛出一个execption(JavaFX事件调度程序线程和我的netork-read线程不一样) - 我理解这种行为。
Now when I create a new Stage
inside the thread, the system throws an execption (JavaFX event dispatcher thread and my netork-read thread are not the same) - I understand this behaviour.
但是另一方面,我将网络阅读器中的文本附加到现有的 TextArea
或添加/删除 ListView< String> <中的一些项目/ code> - 这不会抛出异常 - 为什么?我认为JavaFX是单线程的(ui库部分)。这与Swing中的相同:有时它有效,有时你只有垃圾(因为EDT)?
But the other side is, I append the text from the network-reader to an existing TextArea
or add/remove some items in a ListView<String>
- this doesn't throw an exception - why ? I thought JavaFX is singlethreaded (The ui library part). Is this the same thing as in Swing: Sometimes it works and sometimes you have just garbage (Because EDT)?
我的问题:
- JavaFX事件调度程序线程什么时候抛出异常?什么时候没有?
- 是否有关于此的任何好文档
- 使用
Platform.runLater
使用run()$ c是否有更简单(更简洁,更清晰)的方式$ c>方法?结合try catch(或多次捕获),它看起来很奇怪
- When does the JavaFX event dispatcher thread throw an exception and when not ?
- Are the any good documents about this
- Is there an easier (shorter & cleaner) way to use
Platform.runLater
with arun()
method ? In combination with a try catch (or multiple catch), it looks very strange
我知道的用法一个线程中的Platform.runLater
不是那么好(设计解决方案)
I know the usage of Platform.runLater
in a thread isn't that nice (design solution)
推荐答案
这不是抛出异常 - 为什么?因为并非所有这些情况都是正确的......可能,由于性能方面的考虑,可能只是一个错过的功能。
"this doesn't throw an exception - why?" because not all such cases are cought... Possibly, because of performance considerations, possibly, it is just a missed functionality.
与JavaFX对象的所有交互(包括创建)必须在JFX线程上完成,如果要从另一个线程访问这些JFX对象 - 使用runLater或runAndWait方法。如果它现在不抛出异常,它可能会在将来开始抛出异常。任何与JFX对象的交互都可能导致后续操作和事件,这将由某些线程检查程序进行操作 - 您无法确定。
All interactions with JavaFX objects (including creation) must be done on JFX thread, if you want to access those JFX objects from another thread - use runLater or runAndWait methods. If it doesn't throw exception now, it possibly will start to throw exceptions in the future. Any interaction with JFX object may cause a subsequent actions and event, which will be cought by some thread checker - you cannot be sure.
我不认为,有关于这个的任何好文档 - 只是一个简单的规则 - 使用runLater或runAndWait。
I don't think, there is any good documentation on this - just a simple rule - use runLater or runAndWait.
将使用Lambda在JDK 8中提供更短更清洁的方式。
Shorter and cleaner way - will be provided in JDK 8 using Lambda.
这篇关于使用JavaFX Platform.runLater并从不同的线程访问UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!