在JavaFX中将图像加载到ImageView控件上

4

我想在对话窗口中显示项目文件夹中保存的图像,但是当我运行showDialogWithImage方法时,出现了FileNotFoundExcpetion: imgs\pic1.jpg(系统找不到指定的文件),尽管图像位于那里。

我尝试过这种方式来加载图片:
Image image = new Image(getClass().getResourceAsStream(path));,但是遇到了同样的问题。

还有其他可能的方法来将图像加载到ImageView吗?
谢谢您的帮助!

  • 我的Java代码位于项目文件夹中的src\myProject\gui中。

  • path="imgs\pic1.jpg" // imgs位于项目文件夹中

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();

    }
2个回答

5

getClass().getResourceAsStream(path)会从调用类所在的位置开始搜索文件。因此,使用路径"imgs\pic1.jpg",你就是在说这是你的文件结构。

src\myProject\gui\imgs\pic1.jpg

为了让搜索遍历返回,您需要在imgs之前添加额外的分隔符。因此,应该写成:
"\imgs\pic1.jpg"

此外,我认为当你使用反斜线作为分隔符时,需要进行转义。因此:
"\\imgs\\pic1.jpg

或者直接使用斜杠。
"/imgs/pic1.jpg

另一种选择是使用类加载器,它将从根目录搜索,您不需要开始的分隔符。
getClass().getClassLoader().getResourceAsStream("imgs/pic1.png");

0

当你使用路径加载图片时,需要将文件分隔符“\”替换为“/”,例如:

                            String ImageName="MyImage.png";

                            File file = new File("src\\Messages\\Attachements\\Images");

                            try {
                                if (!file.exists()) {
                                    FileUtils.forceMkdir(file);


                                } 

                                }

                            } catch (Exception io) {
                                io.printStackTrace();
                            }
                            Image image = new Image("/Messages/Attachements/Images/"+ImageName=);
                            ImageReceived.setImage(image);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接