JLabel refresh icon with updated image

拥有回忆 提交于 2019-12-23 19:48:35

问题


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.


回答1:


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).



来源:https://stackoverflow.com/questions/10445665/jlabel-refresh-icon-with-updated-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!