JavaFX:如何将 CSS 添加到 FXML 中的图像元素

标签 java css javafx fxml

我有以下 FXML:

<VBox id="customerFormPane" styleClass="customerForm" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.customer.CustomerFormController" >
    <stylesheets>
        <URL value="@customerform.css"/>
    </stylesheets>

    <GridPane>
        <columnConstraints>
            <ColumnConstraints hgrow="ALWAYS" percentWidth="50.0"/>
            <ColumnConstraints hgrow="ALWAYS" percentWidth="50.0"/>
        </columnConstraints>

        <ImageView id="boxImage" fitWidth="100" fitHeight="100">
            <image>
                <Image url="@/com/exmaple/resources/icons/office.png" />
            </image>            
        </ImageView>
    </GridPane>

</VBox>

我想在 CSS 中为图像定义一个边框。我已经在 customerform.css 文件中尝试过此操作:

.customerForm Image, .customerForm ImageView, .customerForm image {

    -fx-background-color: white;
    -fx-border-style: solid;
    -fx-border-color: red;

}

但是没有任何反应,关于如何选择 ImageView 有什么提示吗? (注:图像显示正确)

最佳答案

节点不支持的 CSS 属性将被忽略。在你的情况下,这就是所有这些属性。 Region 提供 -fx-background-color-fx-border-style-fx-border-color > 属性,但 ImageView 不是 Region 的子类。

为了使其正常工作,您需要将图像包装在合适类型的Region中。

示例:

<GridPane>
    <columnConstraints>
        <ColumnConstraints hgrow="ALWAYS" percentWidth="50.0"/>
        <ColumnConstraints hgrow="ALWAYS" percentWidth="50.0"/>
    </columnConstraints>
    <!-- container using pref size as max size to not grow larger than the image -->
    <Pane styleClass="image-container" maxWidth="-Infinity" maxHeight="-Infinity">
        <children>
            <ImageView id="boxImage" fitWidth="100" fitHeight="100">
                <image>
                    <Image url="@/com/exmaple/resources/icons/office.png" />
                </image>            
            </ImageView>
       </children>
    </Pane>
</GridPane>
.image-container {
    -fx-background-color: white;
    -fx-border-style: solid;
    -fx-border-color: red;
}

顺便说一句:您似乎不确定此处哪些选择器是正确的。您需要在选择器中使用节点类型。 .customerForm ImageView#boxImage 将用作选择器。

关于JavaFX:如何将 CSS 添加到 FXML 中的图像元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56486785/

相关文章:

java - 来自 PostgreSQL 序列的 nextVal 在 Hibernate 中多次获取序列

android - Android Mobile 上的宽度不是 100%

javascript - 使用 Intersection Observer API 延迟翻译元素

java - 将 javaFX 客户端连接到 NodeJs 服务器

java - 如何将本地坐标转换为JavaFX图表坐标

Java - System.setProperty javax.net.ssl.keyStore - 引用 Jar 中的 key 文件

java - Eclipse 中的 JPA 项目和 EJB 项目有什么区别?

java - 无法从文件 Java.Using Netbeans 读取图像

css - 有没有一种简单的方法来设置 svg 路径元素的样式,例如带有 3d 边框的 div?

java - 如何禁用子像素渲染?