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

Adding Keyboard Event Handling: Using KeyEvents<br />

I think that is enough background information for us to move on to implementing KeyEvent processing for the game,<br />

so add a line of code after your screen WIDTH and HEIGHT constant declarations, and declare four Boolean variables<br />

named up, down, left, and right, using a single compound declaration statement, shown in Figure 9-9. Since the<br />

default value for any Boolean value is false (which will signify a key which is not being pressed, that is, a key which is<br />

currently released), we do not have to explicitly initialize these variables. This is done by using the following line of<br />

<strong>Java</strong> code, which is also shown error-free at the top of Figure 9-9:<br />

boolean up, down, left, right;<br />

Figure 9-9. Add a .setOnKeyPressed() function call off a scene object and create a new EventHandler object<br />

As you can see at the bottom of Figure 9-9, I put the foundation for my KeyEvent (pressed) handling using the<br />

.setOnKeyPressed() method call off of the Scene object named scene, which I have instantiated in the previous line of<br />

code. Inside of this method call I create a new EventHandler just like we did for our action events.<br />

The code, which as you can see has an error message attached to it until you import a KeyEvent class, looks like this:<br />

scene.setOnKeyPressed(new EventHandler() { your .handle() method will go in here });<br />

Use an Alt-Enter work process to select an import javafx.scene.input.KeyEvent option seen in Figure 9-9, to<br />

remove this error message. Next, let’s take a look at the .handle() method we need to write to process the KeyEvent.<br />

www.it-ebooks.info<br />

199

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

Saved successfully!

Ooh no, something went wrong!