Javafx 报错:Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found 解决办法

在添加title图标时,javafx报错
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found

在这里插入图片描述
报错代码如下:
在这里插入图片描述

    public void start(Stage stage) throws Exception {

        stage.setTitle("JavaFx App");
        stage.getIcons().add(new Image("resource/image/test.png"));
        stage.show();
    }

查看报错代码
在这里插入图片描述
在这里插入图片描述
显示指定资源为空时,报错找不到资源区文件
说明根本就没找到我们的图片文件

所以我们选择跟Image方法,查看他是如何从我们的url中提取的路径
在这里插入图片描述

public Image(@NamedArg("url") String url) {
	this(validateUrl(url), null, 0, 0, false, false, false);
    initialize(null);
}

跟回到了报错的validateUrl()方法
在这里插入图片描述

    private static String validateUrl(final String url) {
        if (url == null) {
            throw new NullPointerException("URL must not be null");
        }

        if (url.trim().isEmpty()) {
            throw new IllegalArgumentException("URL must not be empty");
        }

        try {
            if (!URL_QUICKMATCH.matcher(url).matches()) {
                final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                URL resource;
                if (url.charAt(0) == '/') {
                    resource = contextClassLoader.getResource(url.substring(1));
                } else {
                    resource = contextClassLoader.getResource(url);
                }
                if (resource == null) {
                    throw new IllegalArgumentException("Invalid URL or resource not found");
                }
                return resource.toString();
            }
            // Use URL constructor for validation
            return new URL(url).toString();
        } catch (final IllegalArgumentException e) {
            throw new IllegalArgumentException(
                    constructDetailedExceptionMessage("Invalid URL", e), e);
        } catch (final MalformedURLException e) {
            throw new IllegalArgumentException(
                    constructDetailedExceptionMessage("Invalid URL", e), e);
        }
    }

由代码可知:
image方法调用http的远程图片可以直接加载成功
在这里插入图片描述

但是本地文件无法加载
所以最后选择使用file协议进行加载

所以最终解决办法为

stage.getIcons().add(new Image("file:resource/image/test.png"));

在这里插入图片描述

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

penguinhd

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值