I suppose it's a very simple thing but I just can't get behind it. All I want is to show an image over an ImageView linked to fxml. Here is my code:
package application;
import java.io.File;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
public class Main extends Application
{
@FXML
private ImageView imageView;
@Override
public void start(Stage primaryStage)
{
try
{
AnchorPane root = (AnchorPane)FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("Hello World");
File file = new File("src/Box13.jpg");
Image image = new Image(file.toURI().toString());
imageView = new ImageView(image);
//root.getChildren().add(imageView);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
And my fxml file
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="316.0" prefWidth="321.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.SampleController">
<children>
<ImageView fx:id="imageView" fitHeight="150.0" fitWidth="200.0" layoutX="61.0" layoutY="83.0" pickOnBounds="true" preserveRatio="true" >
</ImageView>
</children>
</AnchorPane>
There should be no problem with the file linking as it works fine when I include the outcommented line. This would be the way it's done in java only but I want to use fxml here as I am using fxml for all other components but it just doesn't work for the ImageView and I don't know why. I have also tried to create a new controller class and link the ImageView there but that neither works. Can anyone help me?
Thanks
imageView
is not initialized at this stage. It will throw exception. – Logos