Game Development Reference
In-Depth Information
Processing Your KeyEvent: Using the Switch-Case
Statement
KeyEvent object processing is a perfect application for implementing Java's highly ef-
ficient
switch-case
statement. We can add a
case
statement for each type of KeyCode
constant that is contained inside of any KeyEvent (named
event
) that is passed into the
.handle() method. A KeyCode can be extracted from a KeyEvent object using a
.getCode()
method. This method is called on the KeyEvent object named event, inside
of the switch() evaluation area. Inside of the switch{} body, the case statements com-
pare themselves against this extracted KeyCode constant, and if there is a match, the
statements after the colon are processed. The break; statement allows processing to exit
the switch-case evaluation, as an optimization.
This event handling switch-case structure should be implemented by using the fol-
lowing Java programming structure, which is also shown highlighted in
Figure 9-10
:
scene
.setOnKeyPressed
(new EventHandler<KeyEvent>() {
@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;
}
}
});