7

I have a problem with loading Images with ImageView on FXML.

My controller class:

public class BoxViewController {
    @FXML
    private Label label_boxID;

    @FXML
    private ImageView boximage;

    public void initData(ObservableList<BoxProperty> observableList,
                         BoxService sBox, 
                         TableView tableview) {
        this.label_boxID.setText(
            String.valueOf(this.boxproperty.getPboxid()));

        Image image = new Image("boximage.jpg");
        this.boximage = new ImageView();
        this.boximage.setImage(image);
    }
}

So, setting the label with a text works, but the image won't appear in my ImageView. For the ImageView, I added an ID to the FXML file:

 <ImageView fx:id="boximage" 
            disable="false" 
            fitHeight="150.0" fitWidth="200.0"
            layoutX="69.0" layoutY="322.0" 
            pickOnBounds="true" 
            preserveRatio="true" />

I'm confused why this is not working because the label works, but the image won't load.
I also checked whether boximage isn't null, but it isn't. There are also no Exceptions.

Kapol
  • 6,383
  • 3
  • 21
  • 46
mathew11
  • 3,382
  • 3
  • 25
  • 32

2 Answers2

14

Maybe it's a source image location issue. According to the comments at this website, from "Maxim", if you use new Image("boximage.jpg");, the root directory is the main project folder and e.g for scene.getStylesheets().add("login.css"); the root folder is src. Maybe you could try this:

Image img = new Image("file:boximage.jpg");
ImageView imageView = new ImageView(img);

Try to move the source image to the main project folder for this code

Just for testing purpose, try to load that image from FXML:

<ImageView id="boxImage" ...>    
   <image>
      <Image url="@boximage.jpg" />
   </image>
</ImageView>
Aubin
  • 14,617
  • 9
  • 61
  • 84
user2151486
  • 778
  • 2
  • 13
  • 25
  • Thank you for your reply, well, I used the BufferdImage from the API to resolve that problem. Actually, I tried your version too, it works also with the FXML-version, the problem was the "loading" of the image into the scene and not reading out of the file. I used BufferedImage because the picture was loaded dynamically. – mathew11 Jun 04 '14 at 13:21
4

This works:

BufferedImage bufferedImage;
bufferedImage = ImageIO.read(new File(this.path));
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
this.boximage.setImage(image);
mathew11
  • 3,382
  • 3
  • 25
  • 32