You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX Maven中ControlFX通知图片路径无效问题求助

ControlFX通知图片资源加载错误解决方法

问题原因

你的代码中图片路径配置存在两处错误:

  1. 误用了Scene Builder特有的@src/main/resources路径格式,Java代码不识别该写法
  2. getResourceAsStream的路径未以/开头,导致以当前类的包路径为基准查找,无法定位到目标资源

正确配置步骤

  1. 确认资源最终位置:Maven项目中src/main/resources下的文件编译后会直接放在classpath根目录,你的图片最终对应路径为classpath:/com/example/pokedb/images/cancelar.png
  2. 选择正确的加载方式:

修正后的代码

public void error(){
    Notifications notifications = Notifications.create();
    notifications.title("Login Error");
    notifications.text("Username or Password incorrect");
    
    // 方式1:通过getResource获取URL加载图片(推荐)
    Image errorImage = new Image(Objects.requireNonNull(
        getClass().getResource("/com/example/pokedb/images/cancelar.png")
    ).toExternalForm());
    notifications.graphic(new ImageView(errorImage));
    
    // 方式2:通过getResourceAsStream加载图片
    // notifications.graphic(new ImageView(new Image(Objects.requireNonNull(
    //     getClass().getResourceAsStream("/com/example/pokedb/images/cancelar.png")
    // ))));
    
    notifications.hideAfter(Duration.seconds(5));
    notifications.position(Pos.BASELINE_CENTER);
    notifications.show();
}

关键注意事项

  • 路径开头的/表示从classpath根目录开始查找,避免相对路径的歧义
  • 确保图片文件确实存在于src/main/resources/com/example/pokedb/images/目录下,编译后会被自动打包到classpath中
  • 使用Objects.requireNonNull做非空校验,避免因资源不存在导致的空指针异常

内容的提问来源于stack exchange,提问作者pabu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 10:32:39