//fix this /
Hint: JavaFX threading
is similar to that of
Swing.
In the last issue, Marek Piechut created a
Swing window that displayed a simple table and
challenged readers to find the error in his code,
because the resulting table was not what he wanted.
The correct answer is #3: you cannot simply reuse one instance of
Component in Container. Container adds method calls (addImpl),
removing the previous parent from the added component (see
Javadoc for the Component.addImpl method). This way it will be
rendered only in the last place its added.
2 THE CODE
Consider the following Java code that demonstrates a thread retrieving
data from a remote (and possibly slow) datasource, and updates
a JavaFX ProgressBar control. Note that the isComplete() and
getRemoteProgress() methods are not APIs they are just demonstrative.
JAVA IN ACTION
final ProgressBar pb = new ProgressBar(0);
new Thread(new Runnable() {
public void run() {
while (! isComplete()) {
// Retrieve chunk of data...This issues challenge comes from Jonathan Giles, a software
engineer in the JavaFX team at Oracle.
1 THE PROBLEM
JavaFX 2.0 allows for rich client applications to be built in
pure Java or in any other Java Virtual Machine language.
(Excellent support already exists in languages such as Groovy
and Scala see GroovyFX and ScalaFX.) JavaFX has a
modern, high-performance graphics engine sitting beneath a
powerful scene graph with high-quality UI controls, as well
as a number of other features. As with any UI toolkit, there
are things to watch out for heres one of them.
// Update progress value
pb.setProgress(getRemoteProgress());
}
}
}).start();
3 WHAT S THE FIX?
Is this code guaranteed to work in all environments? If not,
what needs to change?
1) Yes. The ProgressBar will always correctly reflect the remote
progress value.
2) Yes, but only if the ProgressBar is instantiated and added to the
JavaFX scene from within the external thread.
3) No. The ProgressBar must always be updated from the JavaFX
application thread.
4) No. JavaFX does not support working with the Thread class
everything must be done on a single JavaFX application thread.
ABOUT US
blog
GOT THE ANSWER?
Look for the answer in the next issue. Or submit your own code challenge!