通过代码在 ImageView 中加载图像 [英] Loading an image in ImageView through code

查看:23
本文介绍了通过代码在 ImageView 中加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用scenebuilder for javafx 构建了我的应用程序.我有一个人必须上传图像的表格.我用了这段代码

I have built my application using scenebuilder for javafx. I have a form where a person has to upload an image. I used this code

public void photoChooser(ActionEvent evt) {
    System.out.println("photoChooser method is called");
    try{
         FileChooser fileChooser= new FileChooser();
         fileChooser.setTitle("Choose a file");
         File file = fileChooser.showOpenDialog(stagehere);
         if(file != null){
             System.out.println(file);
             String img = file.toString();
             //Image image = new ImageIcon(img);           

             try{

         //    image= new Image();
             Image image = new Image(img);

             } catch (Exception e) {System.out.println("Can't upload image " + e);}


             //employeeImage.setImage(image);
             try{
            // employeeImage.setImage(image);
             } catch(Exception e){System.out.println("Can't set the image" + e);}
             employeeImage.setFitWidth(150);
             employeeImage.setFitHeight(150);
         }

我得到了这个错误photoChooser 方法被调用A:imagesfbstatusasd.jpg无法上传图像 java.lang.IllegalArgumentException:无效 URL:未知协议:a

推荐答案

Image 的构造函数需要一个 URL 而不是文件路径.因此,如果字符串中有一个:",则到该点为止的所有内容都被解释为协议(通常类似于 httpfileftp).

The constructor of Image expects an URL and not a file path. Therefore if there is a ":" in the string, everything up to that point is interpreted as the protocol (normally something like http, file or ftp).

你必须换行

String img = file.toString();

String img = file.toURI().toURL().toExternalForm();

这会在转换为字符串之前从文件中获取 URL.我首先转换为 URI,因为 File.toURL 已弃用,这是建议的解决方法".

This gets the URL from the file before converting to string. I converted to URI first since File.toURL is deprecated and that's the suggested "workaround".

这篇关于通过代码在 ImageView 中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆