Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1
Chapter 22 ■ SCoring engine: Creating the SCore Ui LayoUt and SCoring the Content

Now that all of the objects we are going to be looking at inside of the createQAprocessing() method
have been declared so that they are visible to the entire class, we can continue coding the a1Button event
handling with an if (picked == Q1S2 && pickS1 == 0) { ... } structure that lives inside the a1Button
event-handling construct.
Declare a rightAnswer integer and rightAnswers Text object at the top of the class as part of the
compound declaration statements for int variables and Text objects, as we are about to write Java 9 code that
will utilize these.
What we are going to do inside this if() construct is (if Button 1 contains the right answer) to add 1
to the rightAnswer integer and then set a rightAnswers Text object to this rightAnswer value by using a
.setText() method call. Inside the .setText() method we’ll use a String.valueOf() method to convert the
rightAnswer integer to a String value and use .setText() to set scoreCheer to Great Job!. The code for correct
answer processing, which in the case of Q1S1 option 0 (the first answer option) is correct (a right answer),
should look like the following code, as highlighted in Figure 22-26. It has been coded in two lines (four lines,
including lambda expression) to allow 20 board square score logic processing Java constructs to fit in 120
lines of code inside the createQAprocessing() method body.


a1Button.setOnAction(ActionEvent event) -> {
if (picked == Q1S1 && pickS1 == 0) { rightAnswer = rightAnswer + 1;
rightAnswers.setText(String.valueOf(rightAnswer)); scoreCheer.setText("Great Job!");
}
});


To be able to display this rightAnswer integer, we need to add a rightAnswers Text object to your UI
design in createScoreNodes(). This is done using the copy-and-paste technique. Copy the scoreRight block
of Java code directly underneath itself. Set the color to Black and the X position to 96. The Y position should
stay the same so as to align the “right” Text objects. Set the initial text value to zero by using the “0” String
value in the constructor method.


Figure 22-26. Code a compact if() statement evaluating Q1S1 and pickS1 to see whether the a1Button answer
is a correct one

Free download pdf