Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1
Chapter 10 ■ User InterfaCe DesIgn InteraCtIvIty: event hanDlIng anD ImagIng effeCts

scene.setOnKeyPressed(new EventHandler() {
@Override
public void handle(KeyEvent event) {
switch (event.getCode()) {
case UP: up = false; break;
case DOWN: down = false; break;
case LEFT: left = false; break;
case RIGHT: right = false; break;
case W: up = false; break;
case S: down = false; break;
case A: left = false; break;
case D: right = false; break;
}
}
});


Next, let’s switch back into Java coding mode and implement event handling for your user interface
design.


Finishing Your UI Design: Coding the Event Handling


Let’s finish your top-level UI design by writing Java statements inside of your ActionEvent EventHandler
structures inside of the .handle() method. This method clears and then adds Text objects to the
infoOverlay TextFlow object and sets the correct section imagery in your compositing pipeline using the
.setBackground() and .setImage() method calls. As you can see in Figure 10-1, I always clear the TextFlow
object first using the .getChildren().clear() method call, and then I use the .getChildren.addAll() method
call to add the correct Text objects to the TextFlow object. I then use the .setTranslateX() and .setTranslateY()
method calls off the infoOverlay TextFlow to position that container (and layer). After that, I use the
.setBackground() method call to set the uiLayout VBox object background image (for the SplashScreen)
or Background.EMPTY for the other four Button objects, which allows the Color.WHITE background color
to show through. Finally, I use the .setImage() method call to set the boardGameBackPlate ImageView
object with the correct Image object. In the case of the Game Rules (Help) Button, this is a helpLayer Image
object reference. For the first helpButton event handler, this .handle() method code body would include the
following Java statements:


helpButton.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
infoOverlay.getChildren().clear();
infoOverlay.getChildren().addAll(helpText, cardText);
infoOverlay.setTranslateX( 130 );
infoOverlay.setTranslateY( 360 );
uiLayout.setBackground(Background.EMPTY);
boardGameBackPlate.setImage(helpLayer);
}
} );

Free download pdf