Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to add an image in Javafx?

Tags:

java

javafx

I don't understand is how to add a simple image. I imported everything and followed what they said on this page:

http://www.java2s.com/Code/Java/JavaFX/LoadajpgimagewithImageanduseImageViewtodisplay.htm

Javafx code

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class test extends Application {

    @Override
    public void start(Stage stage) {
        stage.setTitle("HTML");
        stage.setWidth(500);
        stage.setHeight(500);
        Scene scene = new Scene(new Group());
        VBox root = new VBox();    

        final ImageView selectedImage = new ImageView();   
        Image image1 = new Image(test.class.getResourceAsStream("C:\\Users\\user\\Desktop\\x.jpg"));

        selectedImage.setImage(image1);

        root.getChildren().addAll(selectedImage);

        scene.setRoot(root);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Error

    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Input stream must not be null
    at javafx.scene.image.Image.validateInputStream(Image.java:1110)
    at javafx.scene.image.Image.<init>(Image.java:694)
    at prototype.test.start(test.java:23)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191)
like image 543
Asperger Avatar asked May 09 '16 08:05

Asperger


1 Answers

Class.getResourceAsStream tries to load an element in the classpath. It's not meant to load files unless they are included in the classpath. To load a file outside of the classpath, use a FileInputStream instead:

Image image1 = new Image(new FileInputStream("C:\\Users\\user\\Desktop\\x.jpg"));

Or use the Image(String) constructor and pass the URL of the file:

Image image1 = new Image(new File("C:\\Users\\user\\Desktop\\x.jpg").toURI().toURL().toExternalForm());
like image 93
fabian Avatar answered Oct 13 '22 11:10

fabian