Monday, May 14, 2012

JavaFX 2.0 Layouts: GridPane

Here is the third tutorial in JavaFX 2.0 Layout series. It's about GridPane layout. GridPane lays out its children within a flexible grid of rows and columns. If a border and/or padding is set, then its content will be layed out within those insets. A grid pane is useful for creating forms or any layout that is organized in rows and columns.

 In this example our goal is to demonstrate how GridPane works, so I will create simple application with 20 buttons, to show and demonstrate it. I will use 2D arrays for creating buttons, because creating manually a large amount of buttons its pretty boring.

GridPane
GridPane

If you still have problems with creating Java project for JavaFX 2.0 in Eclipse IDE, click on the image below.


javafx 2


Here is the code of our GridPane example.


First we create an instance of a GridPane. Here we have 2D array of buttons with value of 5,5. These numbers are representing number of columns and rows.




Now here we have two for loops used for creating 2D array of buttons with columns and rows values i,j. Also here we set  preferred  size of buttons. First number indicates prefWidth - the override value for preferred width and second number indicates prefHeight - the override value for preferred height. 




And at the end we are adding that buttons to gridPane, and here we come to the most important thing to realize about how GridPane works, is to know what are column and row. Column is a vertical line and row is a horizontal line.


Also we could modify a little bit our example by adding padding and horizontal and vertical gap. Here is the code bellow, and image how that modification would look.


4 comments:

  1. If you are doing a series on layout, it could be a good idea to include MigPane (MigLayout for JavaFX) as well.

    http://www.miglayout.com/
    http://tbeernot.wordpress.com/2011/03/11/javafx-2-0-ea-and-miglayout/

    ReplyDelete
  2. Thanks for the comment. I'll take look at that.

    ReplyDelete
  3. If I`m looking to the GridPane layout and TilePane layout I don't see big differences, what should I use to output image thumbnails in an application. Thanks.

    ReplyDelete