问题描述
我正在尝试进行图像处理实验.基本上,我有一个由计时器连续更新的图像,并在JLabel中显示该图像.
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.
我的问题是JLabel无法刷新图像.
My problem is that JLabel does'nt refresh the image.
这是我的计时器代码:
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.
图像已显示,但JLabel从未刷新我的图像.我测试了我的代码,如果我在两个不同的图像之间进行夹工作,则可以正常工作.
Image is displayed but JLabel never refresh my image.I tested my code and is working if I swich between two different images...
我每次创建最后一张图片时都重复一次,并用时间戳重命名.
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();
将所有内容替换为:
label.setIcon(icon);
如果此时标签不可见,则将其声明为外部类的类属性,或声明为与frame
相同的级别(显然可以在该代码段中访问).
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).
这篇关于JLabel刷新具有更新图像的图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!