Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

java - Load image to ImageView JavaFX

I would like to display image(saved in project folder) in dialog window, but when I run my method showDialogWithImage I get FileNotFoundExcpetion: imgspic1.jpg (The system cannot find the file specified), although the image is located there.

I have tried load image on this way too:
Image image = new Image(getClass().getResourceAsStream(path));, but got the same problem.

Are there some others possibilities to load image to ImageView ?
Thank you for help!

  • My Java code is located in srcmyProjectgui in project folder.

  • path="imgspic1.jpg" // imgs is located in project folder

public void showDialogWithImage(String path) {
        final Stage dialogStage = new Stage();

        logger.info(path);

        InputStream is = null;
        try {
            is = new FileInputStream(path); // here I get FileNotFoundException
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Image image = new Image(is);
        ImageView view = new ImageView();
        view.setImage(image);

        Button btnOK = new Button("OK");
        btnOK.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                dialogStage.close();
            }
        });

        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.setScene(new Scene(VBoxBuilder.create()
                .children(view, btnOK).alignment(Pos.CENTER)
                .padding(new Insets(35)).build()));
        dialogStage.show();

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

getClass().getResourceAsStream(path) will start its file search from the location of the calling class. So by using this path "imgspic1.jpg", you're saying this is your file structure

srcmyProjectguiimgspic1.jpg

To have the search traverse back, you need the extra separator before imgs. So

"imgspic1.jpg"

Also, I think when you use a back slash as separator, you need to escape it. So

"\imgs\pic1.jpg

Or just use forward slash

"/imgs/pic1.jpg

Another option is to use a class loader, that will search from the root, where you don't need the beginning separator

getClass().getClassLoader().getResourceAsStream("imgs/pic1.png");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...