JavaFX-将图片插入按钮后,GridPane行的高度增加

问题描述 投票:0回答:1

我有一个按钮网格。当我单击按钮时,将ImageView插入其中,并且由于某种原因,单元格的高度增加了。我不明白为什么以及如何解决它。如何使像元大小恒定?

enter image description here

单击按钮后,第一行的高度增加。

enter image description here

我的控制器类:

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


                    }
                });

            }
        }
    }
}
button javafx imageview gridpane
1个回答
0
投票

GridPane的默认行为是尝试将所有单元格调整为其内容的首选大小。 (如果有多余的可用空间,它将尝试均匀分配它,或者根据在节点上设置的约束或行或列约束进行分配。)将图像添加到按钮时,会增加按钮的首选高度,因此会增加分配给包含该按钮的单元格的空间。

您可以通过在RowConstraints上设置GridPane(更改垂直行分配给每一行的方式)和ColumnConstraints(控制水平行分配给每一列的行)来更改默认行为。

如果要完全限制每行的高度,请设置所有行的minprefmaxHeight

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

如果要按比例设置高度,请使用setPercentHeight()

for (int j = 0 ; j < 5 ; j++) {
    RowConstraints rc = new RowConstraints();
    rc.setPercentHeight(100.0 / 5);
    gameTable.getRowConstraints().add(rc);
}
© www.soinside.com 2019 - 2024. All rights reserved.