JavaFX Maven中ControlFX通知图片路径无效问题求助
ControlFX通知图片资源加载错误解决方法
问题原因
你的代码中图片路径配置存在两处错误:
- 误用了Scene Builder特有的
@src/main/resources路径格式,Java代码不识别该写法 getResourceAsStream的路径未以/开头,导致以当前类的包路径为基准查找,无法定位到目标资源
正确配置步骤
- 确认资源最终位置:Maven项目中
src/main/resources下的文件编译后会直接放在classpath根目录,你的图片最终对应路径为classpath:/com/example/pokedb/images/cancelar.png - 选择正确的加载方式:
修正后的代码
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
相关产品推荐
相关产品推荐

