javaeclipseimagejavafxfxml

display an image in FXML


I want to display a certain image in javaFX so I am creating it in the FXML file to manipulate it later on in controller.java file but I keep getting errors after errors. this is the lastest one

Caused by: javafx.fxml.LoadException: Attributes are not supported for writable property elements.
/C:/Users/ASUS/eclipse-workspace/sample/bin/sample/sample.fxml:263
at sample.Main.start(Main.java:12)
Exception running application sample.Main

this is the simple code i wrote:

<ImageView fx:id="imageView" fitHeight="150.0" fitWidth="200.0" layoutX="61.0" layoutY="83.0" pickOnBounds="true" preserveRatio="true" >
                <image url="file:///C:/Users/ASUS/Desktop/projet/logo.png" backgroundLoading="true"/>
</ImageView>

Solution

  • Example FXML which displays an Image:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.image.Image?>
    <?import javafx.scene.image.ImageView?>
    
    <ImageView fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" xmlns="http://javafx.com/javafx/19" xmlns:fx="http://javafx.com/fxml/1">
       <image>
          <Image url="@../../Pictures/Planet.png" />
       </image>
    </ImageView>
    

    This example was created using SceneBuilder, which I recommend rather than writing FXML from scratch by hand.

    If you need to understand resource loading from FXML, how to structure your resource directories, and the @ syntax shown in this answer to load the image from a relative location, see:

    FAQ

    "Image is not a valid type" and when I change it to "image" I get this error instead "Parent element does not support property elements"

    Sorry, StackOverflow mangled the post, leaving out the imports because I didn't indent the code correctly when I first created the answer. I edited the answer to correctly indent the code so that the imports are visible.

    You need to import the right things, perhaps you are not importing a javafx.scene.image.Image or are incorrectly importing a java.awt.Image.