JavaFX:自定义网格窗格中按钮的宽度

JavaFX: Button's width in custom gridpane

我希望在网格窗格中具有相等(最大)宽度的按钮。

当我尝试直接在 FXML 中设置它时 - 它工作得很好。

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.*?>
<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="TestController">
    <children>
        <GridPane AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.bottomAnchor="0"
                  AnchorPane.topAnchor="0">
            <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" percentWidth="50.0"/>
                <ColumnConstraints hgrow="SOMETIMES" percentWidth="50.0"/>
            </columnConstraints>
            <children>
                <Button maxWidth="Infinity" text="Button1" GridPane.columnIndex="0"/>
                <Button maxWidth="Infinity" text="Button2" GridPane.columnIndex="1"/>
            </children>

        </GridPane>
    </children>
</AnchorPane>

但是当我想将整个网格分成一个自定义控件时,按钮停止以填充可用宽度。

这是一个 FXML:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.*?>
<?import CustomGridPane?>
<AnchorPane xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="TestController">
    <children>
        <CustomGridPane AnchorPane.leftAnchor="0" AnchorPane.rightAnchor="0" AnchorPane.bottomAnchor="0" AnchorPane.topAnchor="0">
        </CustomGridPane>
    </children>
</AnchorPane>

还有一个扩展名:

public class CustomGridPane extends GridPane {

    private Button button1 = new Button("button1");
    private Button button2 = new Button("button2");

    public CustomGridPane() {
        super();
        button1.maxWidth(Double.MAX_VALUE);
        button2.maxWidth(Double.MAX_VALUE);

        getColumnConstraints().add(new ColumnConstraints());
        getColumnConstraints().add(new ColumnConstraints());
        getColumnConstraints().get(0).setPercentWidth(50);
        getColumnConstraints().get(0).setHgrow(Priority.SOMETIMES);
        getColumnConstraints().get(1).setPercentWidth(50);
        getColumnConstraints().get(1).setHgrow(Priority.SOMETIMES);

        add(button1, 0, 0);
        add(button2, 1, 0);
    }
}

我是不是漏掉了什么?

您正在使用 maxWidth 属性 getter 而不是方法 setMaxWidth (setter).

请查看按钮的文档here

public final double maxWidth(double height)

Called during layout to determine the maximum width for this node. Returns the value from computeMaxWidth(forHeight) unless the application overrode the maximum width by setting the maxWidth property.

用 maxWidth(...) 替换这两行:

    button1.setMaxWidth(Double.MAX_VALUE);
    button2.setMaxWidth(Double.MAX_VALUE);

这也可以在场景生成器中实现...

我在创建计算器时需要这个,按钮在网格窗格中。

快乐编码 (: