Search code examples
javaswingjlabelimageicon

why this code doesn´t work: jLabel setIcon?


I´m trying to set the icon for a jLabel object and it doesn´t work. I use a method that returns a ImageIcon object if the .getClass().getResource(path) is different from null, and if the resource is null it display a message "The resource couldn´t be found: path to the file", but the file is there!!!. If i don´t select a file a default ImageIcon is apply instead and this work without problems. I don´t know why this doesn´t work.

 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());
    }
} 

Solution

  • Try to add

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

    after adding Icon