Search code examples
buttonjavafximageviewgridpane

JavaFX - GridPane row increases in height after inserting a picture into a button


I have a gridpane of buttons. When I click on a button an ImageView is inserted into it and for some reason the cell height increases. I can't understand why and how can I fix it. How to make cell size constant?

enter image description here

after button click the first row height increases.

enter image description here

My Controller class:

public class Controller {
    public GridPane gameTable;
    public Label score1;
    public Label score2;
    Image openImage = new Image(getClass().getResourceAsStream("/open.jpg"));
    MyButton open1;
    MyButton open2;
    Player player1 = new Player();
    Player player2 = new Player();
    Player currentPlayer = player1;

    public void initialize(){
        System.out.println(gameTable.getRowCount()+" "+gameTable.getColumnCount());
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 5; j++) {

                MyButton btn = new MyButton(i);
                btn.setMaxWidth(Double.MAX_VALUE);
                btn.setMaxHeight(100);
                gameTable.add(btn, i, j);
                btn.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent actionEvent) {

                        ImageView iv = new ImageView(openImage);
                        iv.setPreserveRatio(true);
                        iv.setFitWidth(btn.getWidth()-10);
                        btn.setGraphic(iv);


                    }
                });

            }
        }
    }
}

Solution

  • The default behavior of a GridPane is to try to size all the cells to the preferred size of their content. (If there's extra space available, it'll try to allocate it evenly, or according to constraints set on the nodes or row or column constraints.) When you add the image to the button, you increase the button's preferred height, so you increase the space allocated to the cell containing that button.

    You can change the default behavior by setting RowConstraints on the GridPane (to change how vertical space is allocated to each row) and ColumnConstraints (to control horizontal space allocated to each column).

    If you want to fully constraint the height of each row, set the min, pref, and maxHeight of all rows:

    for (int j = 0 ; j < 5 ; j++) {
        RowConstraints rc = new RowConstraints();
        rc.setMinHeight(100);
        rc.setPrefHeight(100);
        rc.setMaxHeight(100);
        gameTable.getRowConstraints().add(rc);
    }
    

    If you want to set the heights proportionally, use setPercentHeight():

    for (int j = 0 ; j < 5 ; j++) {
        RowConstraints rc = new RowConstraints();
        rc.setPercentHeight(100.0 / 5);
        gameTable.getRowConstraints().add(rc);
    }