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.
FXML is an XML-based user interface markup language created by Oracle Corporation for defining the user interface of a JavaFX application. FXML presents an alternative to designing user interfaces using procedural code, and allows for abstracting program design from program logic.
It is also possible to assign the controller class directly from the FXML file. In order to do that, you should first open your FXML file and add the following code on the first line of the file right after declarations. Example: Since my controller is inside the package name “view”, my fx: controller = “view.
Create a FileInputStream representing the image you want to load. Instantiate the Image class bypassing the input stream object created above, as a parameter to its constructor. Instantiate the ImageView class. Set the image to it by passing above the image object as a parameter to the setImage() method.
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>
This works:
BufferedImage bufferedImage;
bufferedImage = ImageIO.read(new File(this.path));
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
this.boximage.setImage(image);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With