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

It is important to note that you do not have to use lambda expressions to replace traditional <strong>Java</strong> methods! In<br />

fact, if you want your code to be compatible with <strong>Java</strong> 7, for instance, if you want your code to also work in Android<br />

5.0, which uses <strong>Java</strong> 7, you do not have to utilize lambda expressions. However, since this is specifically a <strong>Java</strong> 8 game<br />

development title, and since lambda expressions are the major new feature of <strong>Java</strong> 8, and since NetBeans will convert<br />

your <strong>Java</strong> methods to lambda expressions for you, as you are about to see, I have decided to utilize them in this book.<br />

Let’s take a closer look at the work process for getting NetBeans to convert your <strong>Java</strong> methods into lambda<br />

expressions for you. As you can see in Figure 9-5, you currently have wavy yellow warning highlights in your code.<br />

Figure 9-5. Mouse-over wavy yellow warning highlight, and reveal a “inner class can be turned into a lambda” pop-up<br />

When you mouse-over these, they will give you a “This anonymous inner class creation can be turned into a<br />

lambda expression,” message. This lets you know that NetBeans 8.0 may be willing to write some lambda expression<br />

code for you, which is really nifty.<br />

To find out, you’ll need to leverage your trusty Alt-Enter work process, and as you can see there is a lambda<br />

expression option that will have NetBeans rewrite the code as a lambda expression. The original code looked like this:<br />

gameButton.setOnAction(new EventHandler() {<br />

@Override public void handle(ActionEvent event) {<br />

splashScreenBackplate.setVisible(false);<br />

splashScreenTextArea.setVisible(false);<br />

}<br />

});<br />

192<br />

The lambda expression that NetBeans codes is much more compact and looks like the following <strong>Java</strong> 8 code:<br />

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

splashScreenBackplate.setVisible(false);<br />

splashScreenTextArea.setVisible(false);<br />

});<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!