Pro Java 9 Games Development Leveraging the JavaFX APIs

(Michael S) #1
Chapter 7 ■ IntroduCtIon to JavaFX 9: overvIew oF the JavaFX new MedIa engIne

an inner class inside of your current JavaFX public void .start() method structure (which you can reference
in Figure 6-7, to refresh your memory):


public void start(Stage primaryStage) {
Button btn = new Button;
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!);
}
}
new AnimationTimer() {
@Override
public void handle(long now) {
// Program logic that gets processed on every pulse which JavaFX processes
}
}.start();
// Rest of start() method code regarding Stage and Scene objects is in here
}


The previous programming logic shows how the AnimationTimer inner class could be constructed
“on the fly,” as well as how Java dot chaining works, as a .start() method call to the AnimationTimer
superclass is appended to the end of a new AnimationTimer() constructor. In one statement, you have the
AnimationTimer creation (new keyword), declaration (constructor method), and execution (start() method
call chained to the AnimationTimer object construct).
If you want to create a more complex AnimationTimer implementation for something central to your
game logic, such as Collision Detection, it would be a better approach (that is, a better pro Java 9 game
design) to make game timing logic into its own (custom) AnimationTimer subclass, instead of an inner class.
This is especially true if you are going to be creating more than one AnimationTimer subclass so that you can
implement custom pulse event processing. You can have more than one AnimationTimer subclass running
at the same time, but I recommend that you don’t get carried away and use too many AnimationTimer
subclasses but instead optimize your Java code and just use one.
To create your own AnimationTimer class called BoardGamePulseEngine using the Java extends
keyword in conjunction with an AnimationTimer superclass, implement this AnimationTimer class
definition and these required AnimationTimer superclass methods to create your “empty” JavaFX pulse
board game logic timing engine.


public class BoardGamePulseEngine extends AnimationTimer {
@Override
public void handle(long now) { // Program logic here that gets processed on every pulse
}
@Override
public void start() {
super.start();
}
@Override
public void stop() {
super.stop();
}
}

Free download pdf