5-to-9
5-to-9

Reputation: 649

JavaFX's version of WPF's UniformGrid?

I'm starting with JavaFX on a new application and I want to get a layout on screen identical to WPF's UniformGrid. There's TilePane but it's different (similar to WrapPanel I guess).

My approach so far would be (for a collection [size = N] I want to display as "tiles"):

  1. Use a TilePane t.
  2. t.setPrefRows( ROUNDUP( sqrt(N)))

That's probably not the best approach. Do you know a better solution? Maybe a resizable one?

Upvotes: 1

Views: 444

Answers (1)

jewelsea
jewelsea

Reputation: 159416

It sounds like you want a layout which:

  1. Has a fixed number of cell nodes in each row.
  2. Each cell node has the same height and width.

I'm not familiar with WPF or UniformGrid, but I think the above is what you want.

TilePane likely isn't a Good Fit

It seems like TilePane would be a good fit for this, but, as you found out, it doesn't really exhibit this behaviour out of the box. With a TilePane, you set a preferred number of rows, but as you resize the TilePane the number of rows and the number of columns can change as the tiles are rearranged to fit the available area.

Use a GridPane with Binding and Preference Settings or Constraints

To get a fixed number of cells per row, use a GridPane. A GridPane will keep a fixed number of rows and columns as it resizes. To ensure that each cell node has the same height and width, you can listen to the height and width properties of the GridPane and, on change, set the min/max/preferred sizes of the child elements so that they all have the same size. Or set some constraints on the GridPane rows and columns such as setPercentWidth and setPercentHeight.

To demonstrate this approach, the ColorChooser sample provides some code for a re-sizable ColorChooser with a fixed number of color swatches per grid row and as the overall containing grid grows or shrinks, the color swatches are grown and shrunk to fit the available area as appropriate. The color swatches themselves don't necessarily maintain the same height/width ratio, but you could easily achieve that by setting appropriate min/max/preferred sizes on the child elements.

smallgrid  mediumgrid

Create Your Own Layout

As an alternative to using change listeners and setting min/max/preferred sizes on children, you could implement your own layout manager by subclassing Pane to create a UniformGrid class and implementing the layoutChildren method. In layoutChildren, arrange the size and position of UniformGrid children as needed. You can refer to the source code of an existing Pane to find an example of how to create your own layouts.

Investigate 3rd party Layouts

The ControlsFX project has a GridView or MigLayout which might provide the functionality of a UniformGrid.

Upvotes: 2

Related Questions