【问题标题】:FXML/CSS: Button with image in center and text in bottomFXML/CSS:图片居中,文本居中的按钮
【发布时间】:2020-05-20 11:47:39
【问题描述】:

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

<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中放置带有文本的标签。

提前致谢!

【问题讨论】:

    标签: css javafx fxml


    【解决方案1】:

    contentDisplay 属性控制图形相对于文本的位置。 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>
    

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

    【讨论】:

    • 谢谢,但不幸的是,alignment="CENTER" 将图像放置在文本的中心,而不是按钮的中心。知道如何解决这个问题吗?
    • @Varest 在这种情况下,您可能需要恢复使用容器作为图形的想法(请参阅更新以获取建议)。您还可以进行实验,例如,将图像视图包装在 HBox 中,并在 HBox 上设置首选宽度和对齐方式。
    • 您的第二个建议效果很好,非常感谢!
    猜你喜欢
    • 2012-01-05
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    相关资源
    最近更新 更多