Java Reference
In-Depth Information
The final step is to initialize our model to the starting position for a Reversi game. The following implementation
of the initBoard() method places the first four pieces in the center of the board.
private void initBoard() {
int center1 = BOARD_SIZE / 2 - 1;
int center2 = BOARD_SIZE /2;
board[center1][center1].setValue(Owner.WHITE);
board[center1][center2].setValue(Owner.BLACK);
board[center2][center1].setValue(Owner.BLACK);
board[center2][center2].setValue(Owner.WHITE);
}
We come back to the model later, but let's switch over to building out the Reversi UI by using some of the basic
dynamic layout mechanisms in JavaFX.
Dynamic Layout Techniques
JavaFX provides a wide variety of layouts that are suitable for different tasks. They range from the versatile bind to
the freeform Pane and Region , which allow you to create an entirely new layout on the fly. There is also a large set of
built-in layouts, including HBox , VBox , AnchorPane , BorderPane , StackPane , TilePane , FlowPane , and GridPane , that
can be composed to accomplish sophisticated layouts.
To demonstrate this, we show how you can build a UI shell for the Reversi application that has absolutely no
static positioned components and that supports dynamic resizing.
Centering Text Using Bind
One of the most powerful facilities in JavaFX is the ability to bind variables. Earlier we showed how binding could be
used to keep the UI and model in sync with no complicated events or listeners.
Another very powerful use of binding is to keep UI components in alignment by binding to their location and
size. This technique can be used to align components to the edges of a window, keep nodes in relative alignment with
each other, or center them inside a container, which is what we show in this example.
To accomplish this, you need to make use of several properties and methods of the Node class in combination
with bind. The common Node members that you need to use when creating bound layouts are listed in Table 5-1 .
To demonstrate, Listing 5-2 is a simple code example that shows how to center the “JavaFX Reversi” title
within a Scene .
Table 5-1. Node Variables Commonly Used in Bind Layouts
Access
Name
Type/Return
Description
layoutXProperty
DoubleProperty Horizontal offset of the Node for layout positioning
public
layoutYProperty
DoubleProperty Vertical offset of the Node for layout positioning
public
prefWidth(double)
Double
Preferred width of the Node (when given the passed-in height for
nodes with a vertical content bias)
public
prefHeight(double) Double
Preferred height of the Node (when given the passed-in width for
nodes with a horizontal content bias)
public
 
Search WWH ::




Custom Search