FXML/CSS: 图像居中,文字在底部的按钮

FXML/CSS: Button with image in center and text in bottom

我有一个带有图标和文本的按钮,但我不知道如何将图标放在按钮的中央,将文本放在按钮的左下角。这是现在的样子:

<Button text="Text" GridPane.rowIndex="0" GridPane.columnIndex="2" prefWidth="135" prefHeight="110" style="-fx-background-color: rgb(176,30,0); -fx-text-fill: rgb(255,255,255); -fx-alignment: BOTTOM_LEFT;">
    <graphic>
        <ImageView>
            <Image url="file:///....png"/>
        </ImageView>
    </graphic>
</Button>

有两件事我试过,但没有奏效: 1. 给ImageView一个单独的对齐属性。 2. 在按钮和 imageView 中放置一个 VXbox,并在 VBox 中放置带有文本的标签。

提前致谢!

contentDisplay property controls the position of the graphic relative to the text. The alignment 属性 控制整体内容的位置。

所以

<Button text="Text" GridPane.rowIndex="0" GridPane.columnIndex="2" prefWidth="135" prefHeight="110" 
    alignment="BOTTOM_LEFT" contentDisplay="TOP" 
    style="-fx-background-color: rgb(176,30,0); -fx-text-fill: rgb(255,255,255);">

或一些类似的组合,应该有效。

如果您更喜欢在 CSS 中设置这些,-fx-alignment: bottom-left; -fx-content-display: top ; 也会这样做。

contentDisplay 属性 不能完全控制图形的位置;您可能需要使用您提出的放置带有图像视图和标签作为图形的容器的想法。在这种情况下,您可能需要居中对齐。 BorderPane 可能比 VBox:

更接近您的需求
<Button GridPane.rowIndex="0" GridPane.columnIndex="2" prefWidth="135" prefHeight="110" style="-fx-background-color: rgb(176,30,0); -fx-text-fill: rgb(255,255,255); -fx-alignment: center;">
    <graphic>
        <BorderPane>
            <center>
                <ImageView>
                    <Image url="file:///....png"/>
                </ImageView>
            </center>
            <bottom>
                <Label text="Text"/>
            </bottom>
        </BorderPane>
    </graphic>
</Button>

您可能还需要尝试设置边框窗格的首选大小,使其填充分配给按钮的区域。