Java Reference
In-Depth Information
You can use a thread to control an animation.
Key
Point
The use of a
Timeline
object to control animations was introduced in Section 15.11, Ani-
mation. Alternatively, you can also use a thread to control animation. Listing 30.2 gives an
example that displays flashing text on a label, as shown in Figure 30.6.
F
IGURE
30.6
The text “Welcome” blinks.
L
ISTING
30.2
FlashText.java
1
import
javafx.application.Application;
2
import
javafx.application.Platform;
3
import
javafx.scene.Scene;
4
import
javafx.scene.control.Label;
5
import
javafx.scene.layout.StackPane;
6
import
javafx.stage.Stage;
7
8
public class
FlashText
extends
Application {
9
private
String text =
""
;
10
11 @Override
// Override the start method in the Application class
12
public void
start(Stage primaryStage) {
13 StackPane pane =
new
StackPane();
14
Label lblText =
new
Label(
"Programming is fun"
);
create a label
label in a pane
15
pane.getChildren().add(lblText);
16
17
new
Thread(
new
Runnable() {
18 @Override
19
create a thread
public void
run() {
run thread
20
try
{
21
while
(
true
) {
22
if
(lblText.getText().trim().length() ==
0
)
change text
23
text =
"Welcome"
;
24
else
25
text =
""
;
26
27 Platform.runLater(
new
Runnable() {
// Run from JavaFX GUI
28 @Override
29
public void
run() {
30 lblText.setText(text);
31 }
32 });
33
34 Thread.sleep(
200
);
35 }
36 }
37
catch
(InterruptedException ex) {
38 }
39 }
40
Platform.runLater
update GUI
sleep
}).start();
41
Search WWH ::
Custom Search