Reputation: 13
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.
Upvotes: 0
Views: 3785
Reputation: 159341
Something to fix:
../
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.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):
FXMLLoader
.fx:controller
attribute that references your FrameController.fx:id
img_view (ensure it is really fx:id
and not just id
).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.
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.
After you create your img object, call:
img.isError();
to see if there was a loading error for the image.
Upvotes: 1