-
Notifications
You must be signed in to change notification settings - Fork 57
/
Example4K.java
125 lines (104 loc) · 3.04 KB
/
Example4K.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import java.util.HashSet;
public class Example4K extends Application
{
public static void main(String[] args)
{
launch(args);
}
static Scene mainScene;
static GraphicsContext graphicsContext;
static int WIDTH = 512;
static int HEIGHT = 256;
static Image left;
static Image leftGreen;
static Image right;
static Image rightGreen;
static HashSet<String> currentlyActiveKeys;
@Override
public void start(Stage mainStage)
{
mainStage.setTitle("Event Handling");
Group root = new Group();
mainScene = new Scene(root);
mainStage.setScene(mainScene);
Canvas canvas = new Canvas(WIDTH, HEIGHT);
root.getChildren().add(canvas);
prepareActionHandlers();
graphicsContext = canvas.getGraphicsContext2D();
loadGraphics();
/**
* Main "game" loop
*/
new AnimationTimer()
{
public void handle(long currentNanoTime)
{
tickAndRender();
}
}.start();
mainStage.show();
}
private static void prepareActionHandlers()
{
// use a set so duplicates are not possible
currentlyActiveKeys = new HashSet<String>();
mainScene.setOnKeyPressed(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent event)
{
currentlyActiveKeys.add(event.getCode().toString());
}
});
mainScene.setOnKeyReleased(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent event)
{
currentlyActiveKeys.remove(event.getCode().toString());
}
});
}
private static void loadGraphics()
{
left = new Image(getResource("left.png"));
leftGreen = new Image(getResource("leftG.png"));
right = new Image(getResource("right.png"));
rightGreen = new Image(getResource("rightG.png"));
}
private static String getResource(String filename)
{
return Example4K.class.getResource(filename).toString();
}
private static void tickAndRender()
{
// clear canvas
graphicsContext.clearRect(0, 0, WIDTH, HEIGHT);
if (currentlyActiveKeys.contains("LEFT"))
{
graphicsContext.drawImage(leftGreen, 64 ,64);
}
else
{
graphicsContext.drawImage(left, 64 ,64);
}
if (currentlyActiveKeys.contains("RIGHT"))
{
graphicsContext.drawImage(rightGreen, 320, 64);
}
else
{
graphicsContext.drawImage(right, 320, 64);
}
}
}