Load image to ImageView JavaFX

后端 未结 2 659
心在旅途
心在旅途 2020-12-17 06:22

I would like to display image(saved in project folder) in dialog window, but when I run my method showDialogWithImage I get FileNotFoundExcpetion: imgs\\pic1.jpg (The system

相关标签:
2条回答
  • 2020-12-17 06:53

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

    src\myProject\gui\imgs\pic1.jpg
    

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

    "\imgs\pic1.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");
    
    0 讨论(0)
  • 2020-12-17 06:54

    when you load an image with path you need replace seperator file "\" with "/" for example

                                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);
    
    0 讨论(0)
提交回复
热议问题