Tuesday, July 3, 2012

JavaFX 2.0 Layout Panes - GridPane

The GridPane is without a doubt the most powerfull and flexible layout pane in JavaFX 2.0.
It lays out its children in a flexible grid of columns and rows and is very similar to Swing´s GridBagLayout or HTML´s table model. This approach makes this pane very well suited for any kind of form (like contact forms on a website).
You have the ability to...
  • apply any Node to a cell (specified by column and row) in the GridPane
  • to let the Node span multiple columns/rows
  • to align the Node in the cell it was applied to
  • to set horizontal or vertical grow for the Node
  • and to apply a margin to be kept around the Node in the cell.
The flexibility of the GridPane also extends to a very flexible API. You can use static class methods like setColumnIndex(node, index) or setRowSpan(node, value), or you can use convenience instance methods like gridpane.add(node, column, row, columnSpan, rowSpan).

  • You don´t have to set the maximum number of columns or rows in the GridPane as it will grow automatically.
  • The size of one column is automatically determined by the widest Node in this column, the height of each row is determined by the tallest Node in the row.
The last note is probably the most important fact about the GridPane as it has to be considered for the column/row and the column span/row span of every single Node in order to get the layout you want.
For more complex layouts it is a very good idea to draw the layout on a piece of paper and to draw all lines for the columns and rows. This will ease development because you can diretly see in which cell you have to put each Node and how many rows or columns they have to span.

Lets have a look at the first simple example: