简体   繁体   中英

JavaFX: How to add CSS to an Image element in FXML

I have the following 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>

I would like to define a border in CSS for the Image. I have tried this in customerform.css file:

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

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

}

But nothing happens, any tip on how to select the ImageView? (Note: the image is displayed correctly)

CSS properties that are not supported by a node are simply ignored. In your case that's all those properties. Region provides the -fx-background-color , -fx-border-style and -fx-border-color properties, but ImageView is not a subclass of Region .

In order for this to work you'd need to wrap the image in a suitable type of Region .

Example:

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

BTW: You seem to be unsure which selectors are the correct ones here. You need to use the node type in the selector. .customerForm ImageView or #boxImage would work as selectors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM