Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1
Chapter 10 ■ User InterfaCe DesIgn InteraCtIvIty: event hanDlIng anD ImagIng effeCts

The KeyCode is then extracted from the KeyEvent object inside of the switch() evaluation area by using
your .getCode() method call, off of an event KeyEvent object. This can be done by using the following Java
switch-case Java code programming structure:


scene.setOnKeyPressed(new EventHandler() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP: up = true; break;
case DOWN: down = true; break;
case LEFT: left = true; break;
case RIGHT: right = true; break; // No break; statement is needed here, if there
// are no more case statements to be added later
}
}
});


This will give you the basic key-pressed event handling structure, which you can add to your pro Java
games and poll these four boolean variables with your code to find out what your user is doing with their
arrow keys. If you instruct NetBeans 9 to turn this Java 7 structure into a Java 8 lambda expression for you,
you’ll get a compact structure. A number of things, such as the public void handle() declaration and the new
EventHandler() declaration, will become implied or assumed (but still exist to the compiler) in
the lambda expression Java 8 code structure. Using a lambda expression will simplify code, reducing it from
a three-deep nested code block to one that is nested only two deep and from eleven lines of code to eight.
Lambda expressions can really be elegant for writing tighter code but do not show you everything that is going
on with the classes (objects), modifiers, and return types that are being used. This is the reason why I am
opting to utilize the more explicit Java 7 (and earlier) code structure, utilized in Java 5 through 7 and prior to the
introduction of Lambda Expressions in Java 8. Both approaches are supported in Java 9.
Your resulting Java 8 lambda expression code structure would look like the following Java code
structure:


scene.setOnKeyPressed(KeyEvent event) -> {
switch (event.getCode()) {
case UP: up = true; break;
case DOWN: down = true; break;
case LEFT: left = true; break;
case RIGHT: right = true; break;
}
});


The next thing that you’ll want to do is to create the polar opposite of the OnKeyPressed structure and
thus create an OnKeyReleased structure. This will use the same code structure, except the true values would
become false values, and the .setOnKeyPressed() method call will instead be a .setOnKeyReleased() method
call. The easiest way to do this is to select the .setOnKeyPressed() structure and copy and paste it underneath
itself. The Java code would look like the following:


scene.setOnKeyReleased(new EventHandler() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP: up = false; break;
case DOWN: down = false; break;

Free download pdf