Java Reference
In-Depth Information
42
// Create a scene and place it in the stage
43 Scene scene =
new
Scene(pane,
200
,
50
);
44 primaryStage.setTitle(
"FlashText"
);
// Set the stage title
45 primaryStage.setScene(scene);
// Place the scene in the stage
46 primaryStage.show();
// Display the stage
47 }
48 }
The program creates a
Runnable
object in an anonymous inner class (lines 17-40). This
object is started in line 40 and runs continuously to change the text in the label. It sets a text
in the label if the label is blank (line 23) and sets its text blank (line 25) if the label has a text.
The text is set and unset to simulate a flashing effect.
JavaFX GUI is run from the
JavaFX application thread
. The flashing control is run from
a separate thread. The code in a nonapplication thread cannot update GUI in the application
thread. To update the text in the label, a new
Runnable
object is created in lines 27-32.
Invoking
Platform.runLater(Runnable r)
tells the system to run this
Runnable
object
in the application thread.
The anonymous inner classes in this program can be simplifed using lambda expressions
as follows:
JavaFX application thread
Platform.runLater
new
Thread(() -> {
// lambda expression
try
{
while
(
true
) {
if
(lblText.getText().trim().length() ==
0
)
text =
"Welcome"
;
else
text =
""
;
Platform.runLater(() -> lblText.setText(text));
// lambda exp
Thread.sleep(
200
);
}
}
catch
(InterruptedException ex) {
}
}).start();
30.9
✓
✓
What causes the text to flash?
Check
30.10
Point
Is an instance of
FlashText
a runnable object?
30.11
What is the purpose of using
Platform.runLater
?
30.12
Can you replace the code in lines 27-32 using the following code?
Platform.runLater(e -> lblText.setText(text));
30.13
What happens if line 34 (
Thread.sleep(200)
) is not used?
A thread pool can be used to execute tasks efficiently.
Key
Point
In Section 30.3, Creating Tasks and Threads, you learned how to define a task class by imple-
menting
java.lang.Runnable
, and how to create a thread to run a task like this:
Runnable task =
new
TaskClass(task);
new
Thread(task).start();
Search WWH ::
Custom Search