I'm trying to make an experiment in image manipulation. Basically I have an image that is continously updated by a timer and i display that image in a JLabel.
My problem is that JLabel does'nt refresh 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 filename is path to my image.
Image is displayed but JLabel never refresh my image. I tested my code and is working if I swich between two different images...
EDIT:
I solved by duplicate every time last image created and renaming with a timestamp.
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 that with something like:
label.setIcon(icon);
If the label is not visible at that point, declare it as a class attribute of the outer class or at the same level as the frame
(which is obviously accessible in that snippet).