Юрий Яхница
Юрий Яхница

Reputation: 427

Java fx-8. How to configure path to local image using fxml file

I have some troubles configuring path to local image in my javaFX application. I want to use icon to my button, but it's not working for local images, only with external resources. This is my code:

            <Button fx:id="magicWangButton" mnemonicParsing="false" onAction="#magicWang" text="Magic wang">
                <graphic>
                    <ImageView fitHeight="20.0" fitWidth="20.0" pickOnBounds="true" preserveRatio="true">
                        <image>
                            <!--<Image url="/fxml/img/magic-wang.png" />-->

                            <Image url="https://i.sstatic.net/y1evM.png" />
                            <!--<Image url="/fxml/img/site-logo.png" />-->
                            <Image url="img/magic-wang.png"/>
                        </image>
                    </ImageView>
                </graphic>
            </Button>

this string work's fine:

<Image url="https://i.sstatic.net/y1evM.png" />

, but others... My image located in path: resources/fxml/img/ all fxml files located in fxml directory. I saw other questions and answers but it uses configuration in java files, but it is not what I looking for.

Upvotes: 0

Views: 1391

Answers (2)

Puce
Puce

Reputation: 38132

The trick is to start the url with "@" and call FXMLLoader.setLocation().

  • relative URLs:
    • @one24.png:
    • @image/two24.png
    • @../three24.png
  • absolute URLs:
    • @/four24.png
    • @/image/five24.png

Please note that I've implemented a utility class: FXMLLoaders

If you stick to the following naming conventions:

  • MyComponent.java
  • MyComponent.fxml (same package as MyComponent.java)
  • MyComponent.properties (same package as MyComponent.java)

you can use the following code:

For fx:root based FXML files:

public MyComponent() {
    FXMLLoaders.loadRoot(this);
}

Otherwise:

Parent root = FXMLLoaders.load(FxmlSampleApplication.class);

The library is available from Maven Central:

<dependency>
    <groupId>org.drombler.commons</groupId>
    <artifactId>drombler-commons-fx-core</artifactId>
    <version>0.13</version>
</dependency>

You can find a full sample which loads images on GitHub.

I've also written a blog post about this utility class and the naming conventions.

Upvotes: 1

fabian
fabian

Reputation: 82461

You can specify a path relative to the fxml by starting the attribute value with @, see Introduction to FXML: Location Resolution

<Image url="@img/site-logo.png" />

Upvotes: 2

Related Questions