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

As you can see in Figure 9-6, this lambda expression that NetBeans wrote for you is not without warnings<br />

itself, as there is a “Parameter event is not used” warning, so we will be removing the event next, to make the<br />

lambda expression even more compact! At some point in time, Oracle will update this code that writes lambda<br />

expressions so that it looks inside of your method code block, sees that there is no event object referenced, and<br />

will remove this as well, and the warning will no longer be generated. Until that time comes, we’ll need to edit<br />

NetBeans’ code ourselves.<br />

Figure 9-6. The lambda expression that NetBeans writes for you has a warning message “Parameter event is not used”<br />

Since we are not using the event variable inside of the code body of this lambda expression, we can remove it,<br />

giving us this following final <strong>Java</strong> 8 lambda expression code, which is quite a bit more simple than the original code:<br />

gameButton.setOnAction((ActionEvent) -> {<br />

splashScreenBackplate.setVisible(false);<br />

splashScreenTextArea.setVisible(false);<br />

});<br />

As you can see the lambda expression requires that the <strong>Java</strong> compiler create the ActionEvent object for you,<br />

replacing a new EventHandler() constructor method call with the ActionEvent object it creates.<br />

If you are wondering why lambda expressions were added to <strong>Java</strong> 8, and how they make it better, they allow a <strong>Java</strong><br />

function (method), especially a “one shot” or inner method, to be written like a statement. They also facilitate<br />

multi-threading.<br />

Before we get into event handling classes in <strong>Java</strong> 8 and <strong>Java</strong>FX, let’s take a look at an update I encountered as I was<br />

writing this chapter, as well as a couple of warning highlights that are appearing, which are not accurate.<br />

www.it-ebooks.info<br />

193

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

Saved successfully!

Ooh no, something went wrong!