28.04.2019 Views

[JAVA][Beginning Java 8 Games Development]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9 ■ Controlling Your Action Figure: Implementing <strong>Java</strong> Event Handlers and Using Lambda Expressions<br />

Processing Your KeyEvent: Using the Switch-Case Statement<br />

KeyEvent object processing is a perfect application for implementing <strong>Java</strong>’s highly efficient switch-case statement.<br />

We can add a case statement for each type of KeyCode constant that is contained inside of any KeyEvent (named event)<br />

that is passed into the .handle() method. A KeyCode can be extracted from a KeyEvent object using a .getCode()<br />

method. This method is called on the KeyEvent object named event, inside of the switch() evaluation area. Inside of<br />

the switch{} body, the case statements compare themselves against this extracted KeyCode constant, and if there is a<br />

match, the statements after the colon are processed. The break; statement allows processing to exit the switch-case<br />

evaluation, as an optimization.<br />

This event handling switch-case structure should be implemented by using the following <strong>Java</strong> programming<br />

structure, which is also shown highlighted in Figure 9-10:<br />

scene.setOnKeyPressed(new EventHandler() {<br />

@Override<br />

public void handle(KeyEvent event) {<br />

switch (event.getCode()) {<br />

case UP: up = true; break;<br />

case DOWN: down = true; break;<br />

case LEFT: left = true; break;<br />

case RIGHT: right = true; break;<br />

}<br />

}<br />

});<br />

Figure 9-10. Add a switch-case statement inside of the public void handle() method setting Boolean direction variables<br />

200<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!