JLabel refresh icon with updated image

I'm trying to do an image manipulation experiment. Basically, I have an image that is constantly updated by a timer, and I display this image in JLabel.

My problem is that JLabel is not updating the image.

Here is my timer code:

Timer timer = new Timer(200, new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            count++;

            System.out.println("timer");
            System.out.println(filename);

            ImageIcon icon = new ImageIcon(filename);

            label = new JLabel();
            label.setIcon(icon);
            label.setText(""+count);

            panel = new JPanel();
            panel.add(label);

            frame.getContentPane().removeAll();
            frame.getContentPane().add(panel);

            frame.repaint();
            frame.validate();

            try{
                FileWriter fstream;

                fstream = new FileWriter(filename,true);

                BufferedWriter out = new BufferedWriter(fstream);

                out.write("text to append");
                out.close();
            }catch (Exception ex){
                System.err.println("Error: " + ex.getMessage());
            }
        }
    });

Where the file name is the path to my image.

The image is displayed, but JLabel never updates my image. I checked my code and worked if I swich between two different images ...

EDIT:

I decided to duplicate every time the last image was created and renamed with a timestamp.

+3
source share
1 answer
label = new JLabel();
label.setIcon(icon);
label.setText(""+count);

panel = new JPanel();
panel.add(label);

frame.getContentPane().removeAll();
frame.getContentPane().add(panel);

frame.repaint();
frame.validate();

Replace all of this with something like:

label.setIcon(icon);

If the label is not visible at this point, declare it as an attribute of a class of the outer class or at the same level as frame(which, obviously, is available in this fragment).

+6
source

All Articles