Home > Mobile >  Setting size of cells in GridPane in order to fit the parent
Setting size of cells in GridPane in order to fit the parent

Time:02-22

Is there a way to make it so the objects/cells of a GridPane are made to fit the parent (TabPane in this instance)? I have been trying this using buttons inside of the GridPane for the past for hours and haven't been able to find a solution.

Here is what I've been trying:

GridPane gPane = new GridPane();
double size = Math.sqrt((tabPane.getTabs().get(0).getContent().getLayoutBounds().getHeight() * tabPane.getTabs().get(0).getContent().getLayoutBounds().getWidth()) / (rows * columns));
for (int i = 0; i < height; i  )
            for (int j = 0; j < width; j  ) {
                array[i][j] = new Button();
                array[i][j].setPrefWidth(size);
                array[i][j].setPrefHeight(size);
                gPane.add(array[i][j], i, j);
            }

When I run this, the size of the cells either don't match the size, or when they do, they do not fit the screen as they should.

CodePudding user response:

This would be a perfect scenario for using RowConstraints and ColumnConstraints to ensure your objects don't resize the gridpane.

From the Javadoc:

By default, rows and columns will be sized to fit their content; a column will be wide enough to accommodate the widest child, a row tall enough to fit the tallest child.However, if an application needs to explicitly control the size of rows or columns, it may do so by adding RowConstraints and ColumnConstraints objects to specify those metrics. For example, to create a grid with two fixed-width columns:

     GridPane gridpane = new GridPane();
     gridpane.getColumnConstraints().add(new ColumnConstraints(100)); // column 0 is 100 wide
     gridpane.getColumnConstraints().add(new ColumnConstraints(200)); // column 1 is 200 wide

You can also size by percentage which may suite your needs better:

Alternatively, RowConstraints and ColumnConstraints allow the size to be specified as a percentage of gridpane's available space:

 GridPane gridpane = new GridPane();
 ColumnConstraints column1 = new ColumnConstraints();
 column1.setPercentWidth(50);
 ColumnConstraints column2 = new ColumnConstraints();
 column2.setPercentWidth(50);
 gridpane.getColumnConstraints().addAll(column1, column2); // each get 50% of width

Source: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/GridPane.html

  • Related