【问题标题】:why this code doesn´t work: jLabel setIcon?为什么这段代码不起作用:jLabel setIcon?
【发布时间】: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 也重新粉刷了吗?如果没有,也放在那里
  • ifelse 语句中也是如此,但仍然不起作用。

标签: java swing jlabel imageicon


【解决方案1】:

尝试添加

this.revalidate();  
this.repaint();  

添加图标后

【讨论】:

  • 我的意思是当我检查时:if (op == JFileChooser.APPROVE_OPTION) 如果是 TRUE ImageIcon 对象是我选择的图片,如果是 FALSE ImageIcon 对象被选择默认情况下:else {SetLibro("/img/blank.jpg"); jLabel47.setIcon(createImageIcon(GetLibro())); }。我听从您的建议,将this.repaint() 放在 if 语句中的 SetIcon(createImageIcon(GetLibro())) 之后。但它在我第一次运行项目时有效,但不再有效。
  • @mKorbel:你的意思是:getIconImage().flush();?因为它不起作用。
  • @MaximShoustin this.revalidate();this.repaint();。还是不行。
  • @Eddy 发布你所有的代码,我无法从 sn-ps 检测到问题
  • @Eddy:请编辑您的问题以包含一个sscce,以展示您所描述的问题。今后,您可以通过点击左侧的empty check mark 来接受此答案。
猜你喜欢
  • 1970-01-01
  • 2010-09-18
相关资源
最近更新 更多