设置 GridPane 中单元格的大小以适合父级

Setting size of cells in GridPane in order to fit the parent

有没有办法让 GridPane 的 objects/cells 适合父级(在本例中为 TabPane)?几个小时以来,我一直在尝试使用 GridPane 内的按钮进行此操作,但未能找到解决方案。

这是我一直在尝试的:

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);
            }

当我 运行 这样做时,单元格的大小要么与大小不匹配,要么当它们匹配时,它们不适合屏幕。

这将是使用 RowConstraints 和 ColumnConstraints 来确保您的对象不会调整网格窗格大小的完美方案。

来自 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

您还可以按百分比调整大小,这可能更适合您的需要:

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

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