我正在尝试为 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());
}
}
最佳答案
尝试添加
this.revalidate();
this.repaint();
添加图标后
关于java - 为什么此代码不起作用 : jLabel setIcon?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19208761/