1
+ import javafx .application .Application ;
2
+ import javafx .stage .Stage ;
3
+ import javafx .scene .Scene ;
4
+ import javafx .scene .Group ;
5
+ import javafx .scene .canvas .Canvas ;
6
+ import javafx .scene .canvas .GraphicsContext ;
7
+ import javafx .scene .image .Image ;
8
+
9
+ import javafx .animation .Timeline ;
10
+ import javafx .animation .KeyFrame ;
11
+ import javafx .util .Duration ;
12
+ import javafx .event .EventHandler ;
13
+ import javafx .event .ActionEvent ;
14
+
15
+ // An alternative implementation of Example 3,
16
+ // using the Timeline, KeyFrame, and Duration classes.
17
+
18
+ // Animation of Earth rotating around the sun. (Hello, world!)
19
+ public class Example3T extends Application
20
+ {
21
+ public static void main (String [] args )
22
+ {
23
+ launch (args );
24
+ }
25
+
26
+ @ Override
27
+ public void start (Stage theStage )
28
+ {
29
+ theStage .setTitle ( "Timeline Example" );
30
+
31
+ Group root = new Group ();
32
+ Scene theScene = new Scene ( root );
33
+ theStage .setScene ( theScene );
34
+
35
+ Canvas canvas = new Canvas ( 512 , 512 );
36
+ root .getChildren ().add ( canvas );
37
+
38
+ GraphicsContext gc = canvas .getGraphicsContext2D ();
39
+
40
+ Image earth = new Image ( "earth.png" );
41
+ Image sun = new Image ( "sun.png" );
42
+ Image space = new Image ( "space.png" );
43
+
44
+ Timeline gameLoop = new Timeline ();
45
+ gameLoop .setCycleCount ( Timeline .INDEFINITE );
46
+
47
+ final long timeStart = System .currentTimeMillis ();
48
+
49
+ KeyFrame kf = new KeyFrame (
50
+ Duration .seconds (0.017 ), // 60 FPS
51
+ new EventHandler <ActionEvent >()
52
+ {
53
+ public void handle (ActionEvent ae )
54
+ {
55
+ double t = (System .currentTimeMillis () - timeStart ) / 1000.0 ;
56
+
57
+ double x = 232 + 128 * Math .cos (t );
58
+ double y = 232 + 128 * Math .sin (t );
59
+
60
+ // Clear the canvas
61
+ gc .clearRect (0 , 0 , 512 ,512 );
62
+
63
+ // background image clears canvas
64
+ gc .drawImage ( space , 0 , 0 );
65
+ gc .drawImage ( earth , x , y );
66
+ gc .drawImage ( sun , 196 , 196 );
67
+ }
68
+ });
69
+
70
+ gameLoop .getKeyFrames ().add ( kf );
71
+ gameLoop .play ();
72
+
73
+ theStage .show ();
74
+ }
75
+ }
0 commit comments