关于swing的图片路径

wswhp 2007-11-05 10:07:50
我用JFileChooser 选择一个图片 然后显示在jfram的jlabel上

选择文件的代码
File file = fcPic.getSelectedFile();
picName = file.getName();
ImageIcon newImage = new ImageIcon(ReporterGUI.class.getResource("picName ")));
picture.setIcon(newImage);

显示图片jlabel
picture = new JLabel(new ImageIcon(ReporterGUI.class.getResource("1.jpg")));


现在只能显示与此java文件同目录的图片 其他目录的不能显示 报错

比如我想选c盘的图片

问题可能出在url那里 应该怎么写代码

急啊
...全文
484 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Ji秋风 2007-11-08
  • 打赏
  • 举报
回复
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = MainFrame.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
log.error("找不到位图文件: " + path);
return null;
}
}
LexChen 2007-11-07
  • 打赏
  • 举报
回复
如果是以后要打包在jar中或者就存储在当前路径或子目录下,那么只要写jar包中的相对路径就可以了,
如: getResource("resources/images/test.jpg");
如果是本地磁盘上的文件,就写绝对路径好了
千里冰封820 2007-11-05
  • 打赏
  • 举报
回复
得到了它的URL,就什么事都可 以做了
千里冰封820 2007-11-05
  • 打赏
  • 举报
回复
File file = fcPic.getSelectedFile();
picName = file.getName();
ImageIcon newImage = new ImageIcon(Toolkit.getDefaultToolkit().createImage(file.toURI().toURL()));
picture.setIcon(newImage);
zhb_821012 2007-11-05
  • 打赏
  • 举报
回复
友情up
issgates 2007-11-05
  • 打赏
  • 举报
回复
fcPic取绝对路径, new ImageIcon是能够设置绝对路径的吧, 具体搜搜.

62,636

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧