Inserting image into ImageView using Javafx


Question

I have a frame controller class where I am reading values from a form(which is created by using Javafx Scene Builder) and inserting information after controlling their validity. What I want to do is just know how to insert an image to an ImageView element on the stage.

public class FrameController {
   @FXML
   private ImageView img_view;
   ....
   @FXML
   public void ButtonClicked() {
   ...


     img_view = new ImageView();
     Image img = new Image("../img/img.jpg");
     img_view.setImage(img);
   ...
   }
}

This just does not work. It runs debugger after I clicked the button that is bound to ButtonClicked() function. Am I missing something? How can I insert an image to the ImageView element on the scene? I will really appreciate your help.

1
0
3/23/2014 10:25:07 PM

Accepted Answer

Something to fix:

  1. The relative path reference ../ will not resolve to a URL which can be loaded by a jar protocol (which is the standard protocol used for loading resources in packaged JavaFX apps). So don't use a relative reference with ..\ in it.
  2. Instead use an absolute reference, for example:

    /com/mycompany/myapp/myproject/img/img.jpg

Some things to check (assuming you have made the change above):

  1. Load your FXML using the FXMLLoader.
  2. In your FXML have an fx:controller attribute that references your FrameController.
  3. In your FXML have an ImageView element which defines the fx:id img_view (ensure it is really fx:id and not just id).
  4. Understand the image loading rules outlined in Sergey's answer to: Where does javafx.scene.image.Image("flower.png") look for flower.png?.
  5. In your controller, add a line:

    System.out.println(FrameController.getClass().getResource(
        "/com/mycompany/myapp/myproject/img/img.jpg").toExternalForm()
    );
    

    this will print out where the system is actually looking for your image.

  6. Ensure that your build system is copying the img.jpg to your class output directory. To do this, after the build completes and assuming the build makes a jar named myapp.jar, run:

    jar xvf myapp.jar

    and see if img.jpg is at the path com/mycompany/myproject/img/img.jpg.

  7. After you create your img object, call:

    img.isError();
    

    to see if there was a loading error for the image.

1
5/23/2017 11:43:22 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon