【发布时间】:2013-10-13 01:51:29
【问题描述】:
我正在尝试为 jLabel 对象设置图标,但它不起作用。如果 .getClass().getResource(path) 与 null 不同,我使用返回 ImageIcon 对象的方法,如果资源为 null,则显示消息“找不到资源:文件的路径”,但文件在那里!!!!如果我不选择文件,则应用默认的 ImageIcon 并且这可以正常工作。我不知道为什么这不起作用。
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {
try {
JFrame upFile = new JFrame();
File fichero = new File("");
File x = new File("");
CopyFile copy= new CopyFile();
JFileChooser upfile = new JFileChooser(fichero.getCanonicalPath());
int op = upfile.showOpenDialog(upFile);
if (op == JFileChooser.APPROVE_OPTION) {
fichero = upfile.getSelectedFile();
File destino = new File(x.getCanonicalPath()+"\\src\\img\\libros_fotos\\"+fichero.getName());
copy.copyFile(fichero, destino);
SetLibro("/img/libros_fotos/"+destino.getName());
jLabel47.setIcon(createImageIcon(GetLibro()));
// commented out as suggested
//this.revalidate();
//this.repaint();
}
else {SetLibro("/img/blank.jpg");
jLabel47.setIcon(createImageIcon(GetLibro()));
// commented out as suggested
//this.revalidate();
//this.repaint(); }
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
【问题讨论】:
-
createImageIcon(GetLibro())是什么Icon? -
是的,我返回一个 ImageIcon 对象或 null。
-
private ImageIcon createImageIcon(String path) { java.net.URL imgURL = getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("File not found: " + path); return null; } }它返回 null 或 Imageicon 对象。 -
你在
else也重新粉刷了吗?如果没有,也放在那里 -
在
if和else语句中也是如此,但仍然不起作用。
标签: java swing jlabel imageicon