0

I am trying to learn how to display images in JavaFX. In order to learn, I tried to create this simple program. However, the image does not display in the application.

package imagedemo;

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.HBox;

public class ImageDemo extends Application
{    
    public static void main(String[] args)
    {
    launch(args);
    }
    
    @Override
    public void start(Stage primaryStage)
    {
        //Create Image and ImageView
        Image image = new Image("file:testImage.JPG");
        ImageView iv = new ImageView(image);
        
        //Create HBox, Scene, and Stage
        HBox hbox = new HBox(iv);
        Scene scene = new Scene(hbox);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

When I run the program, the result is: an empty application window. Are there any solutions that will cause the image to appear on the application as it should?

Edit 1: I am using NetBeans IDE 8.2 for this program in case anyone needs to know.

Edit 2: Here is the full path to file testImage.JPG: full path

Ishaaq
  • 9
  • 2
  • `file:testImage.JPG` is not a valid URL. What is the full path to file `testImage.JPG`? – Abra Jul 25 '20 at 18:58
  • See https://stackoverflow.com/questions/61531317/how-do-i-determine-the-correct-path-for-fxml-files-css-files-images-and-other – James_D Jul 25 '20 at 20:14
  • @Abra Ok, so I replaced the URL with `"file:C:\\Users\\iront\\Documents\\JavaExercises\\ImageDemo\\src\\testImage.JPG` and it seems to work now. I am surprised that the URL `file:testImage.JPG` did not work earlier even though the image was in `package imagedemo` – Ishaaq Jul 25 '20 at 23:33
  • @Ishaaq No, you don't want to use a hard-coded `file` URL for embedded resources. If you read the duplicate you'll see you want to either use the resource path _or_ use methods such as `Class#getResource(String)` (whose argument is the resource path). – Slaw Jul 25 '20 at 23:44

0 Answers0