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 />

Next, let’s use a block copy and paste operation, and copy the .OnKeyPressed() KeyEvent handing structure<br />

underneath itself, changing it to be an .OnKeyReleased KeyEvent handling structure, with false values instead of true.<br />

Creating the KeyPressed KeyEvent Handling Structure<br />

The next thing that we will need to do is to create the polar opposite of the OnKeyPressed structure, and create the<br />

OnKeyReleased structure. This will use the same code structure, except that the true values will become false values,<br />

and the .setOnKeyPressed() method call will instead be a .setOnKeyReleased() method call. The easiest way to do this<br />

is to select the .setOnKeyPressed() structure, and copy and paste it underneath itself. The <strong>Java</strong> code, which is shown in<br />

Figure 9-12, should look like this <strong>Java</strong> structure:<br />

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

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

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

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

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

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

}<br />

});<br />

Figure 9-12. Use a block copy and paste operation to create .setOnKeyReleased() code block, using .setOnKeyPressed()<br />

One of the interesting things that using lambda expressions does by “implicitly” declaring and using classes, such<br />

as the EventHandler class in the instances in this chapter, is that it reduces the number of import statements in the<br />

top of your class code. This is because if a class is not specifically used (its name written) in your code, the import<br />

statement for that class does not have to be in place at the top of your code with the other import statements.<br />

202<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!