Java Reference
In-Depth Information
If opposing anchors are set on the left and right or top and bottom, the sizing behavior changes to stretching
where the child width will be equal to the parent width minus the left and right anchor distances or the parent height
minus the top and bottom anchor distances, respectively. It is also possible to set all four anchors, in which case the
child will resize both dimensions together with the parent.
With a few modifications to the Reversi application we make use of both the alignment and stretching properties
of an AnchorPane to add in a new Restart button to the UI. The first step is to refactor the Reversi constructor to extract
the existing game view into a variable and add in an AnchorPane as the root node:
@Override
public void start(Stage primaryStage) {
TilePane title = createTitle();
TilePane scoreBoxes = createScoreBoxes();
BorderPane game = new BorderPane();
game.setTop(title);
game.setCenter(new StackPane(createBackground(), tiles()));
game.setBottom(scoreBoxes);
Node restart = restart();
AnchorPane root = new AnchorPane(game, restart);
primaryStage.setScene(new Scene(root, 600, 400));
...
Notice that we have also added in a second component to the AnchorPane for the Restart button that we define
later. The rest of the method goes on to set the AnchorPane constraints for the game and restart nodes so that the
former scales together with the scene, and the latter is aligned 10 pixels off the top-right corner:
...
AnchorPane.setTopAnchor(game, 0d);
AnchorPane.setBottomAnchor(game, 0d);
AnchorPane.setLeftAnchor(game, 0d);
AnchorPane.setRightAnchor(game, 0d);
AnchorPane.setRightAnchor(restart, 10d);
AnchorPane.setTopAnchor(restart, 10d);
}
The next step is to create the restart() method that builds the Restart button and wires up an ActionEvent
handler that will reset the model:
private Node restart() {
Button button = new Button("Restart");
button.setOnAction(e -> model.restart());
return button;
}
Finally, you need to implement the restart model function that will restart all the squares to their initial values
and set the turn back to black:
public void restart() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j].setValue(Owner.NONE);
}
 
Search WWH ::




Custom Search