Image not updated [closed]

0

I am making an application where I use a JFileChooser to choose an image, I take that image and I copy it to a folder that is in network. After that it executes a method that shows this image saved in a Label, transformed into icon.

The problem is here: When I try to load a different image and save it with the same name when displaying this image, it still looks like the old one. Just show the new one when I close the application and open again.

Remembering that I want to keep this IMG name as "1.png"

public void testesComChooser() {

            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Somente Imagens", "jpg", "jpeg", "gif", "png");

            chooser.setDialogTitle("Selecione uma foto");
            chooser.setFileFilter(filter);
            chooser.setAcceptAllFileFilterUsed(false);

            int resultado = chooser.showSaveDialog(this);

            if(resultado == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                salvarArquivo(file);
            }else {

            }

        }

        private void salvarArquivo(File img){

            String nomeImg = "1.png";
            String caminho = "C:\imagens\";

            Path pathDiretorio = FileSystems.getDefault().getPath(caminho, nomeImg);

            try {
             //   Files.deleteIfExists(pathDiretorio);
                Files.copy(img.toPath(), pathDiretorio, StandardCopyOption.REPLACE_EXISTING);

            }catch(Exception ex) {
                ex.printStackTrace();
            }

            visualizarImg(nomeImg);

        }

        private void visualizarImg(String nomeImg) {

            String caminho = "C:\imagens\";
            Icon icon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(caminho + nomeImg));
            label.setIcon(icon);
        }
    
asked by anonymous 17.08.2017 / 17:39

1 answer

0

You are using the Toolkit.getImage(String) method that, by > documentation, does not necessarily return the current contents of the file but can return a previously loaded image of that file (uses a cache). The documentation also suggests the what to do: call the flush method of the image returned in the previous call:

  

If the image data contained in the specified file changes, the Image object returned from this method may still contain stale information which was loaded from the file after a prior call. Previously loaded image data can be manually discarded by calling the flush method on the returned Image.

I'd advise using the javax.imagio.ImageIO para ler imagens class - method read (File) - is more modern and does not have this problem with Toolkit .

Note: Toolkit should not be used directly:

  

Most applications should not call any of the methods in this class directly.

    
17.08.2017 / 18:36