28.04.2019 Views

[JAVA][Beginning Java 8 Games Development]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

Now we have the basic key-pressed event handling structure, which we’ll be adding to a bit later, let’s have<br />

NetBeans turn this <strong>Java</strong> 7 code into a <strong>Java</strong> 8 lambda expression for us! After that, we can create a key-released event<br />

handling structure by using a block copy and paste operation, turning the .setOnKeyPressed() to .setOnKeyReleased(),<br />

and the true values to false values. Programming shortcuts are almost as cool as having NetBeans write code for us!<br />

Converting the KeyEvent Handling Structure: Using a <strong>Java</strong> 8 Lambda Expression<br />

Next let’s have NetBeans recode our EventHandler code structure as a lambda expression, which will<br />

simplify it significantly, reducing it from a three-deep nested code block to one that is nested only two deep, and from<br />

eleven lines of code to only eight. These lambda expressions are really elegant for writing tight code, and they are<br />

designed for multi-threaded environments, so whenever possible their usage could result in more optimal Thread<br />

usage! The resulting <strong>Java</strong> 8 lambda expression code structure should look like the following, as shown in Figure 9-11:<br />

scene.setOnKeyPressed(KeyEvent event) -> {<br />

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

case UP: up = true; break; // UP, DOWN, LEFT, RIGHT constants from KeyCode class<br />

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

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

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

}<br />

});<br />

Figure 9-11. Convert the KeyEvent method to a lambda expression; notice that the event variable is used in the switch<br />

www.it-ebooks.info<br />

201

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

Saved successfully!

Ooh no, something went wrong!