我有一个从程序开头的文件夹中读取的图像。该程序将从Internet下载新图像并覆盖旧图像,相同的文件路径和相同的名称,但显示的图像是旧图像。退出并重新加载程序时,将显示新图像。我知道图像没有改变,因为我还尝试从文件路径创建一个新的ImageIcon,并在下载后将其显示在JDialog中,它仍然是旧图像。有什么想法吗?
答案 0 :(得分:4)
然而,只有正确显示的jdialog。即使我调用了frame.validate();原始帧仍显示旧图像。 frame.repaint();
将图像读入内存不会导致组件引用新图像。您仍然需要将Icon添加到使用旧图像的任何组件。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
public class ImageReload extends JFrame implements ActionListener
{
JLabel timeLabel;
JLabel imageLabel;
ImageIcon icon = new ImageIcon("timeLabel.jpg");
public ImageReload()
{
timeLabel = new JLabel( new Date().toString() );
imageLabel = new JLabel( timeLabel.getText() );
getContentPane().add(timeLabel, BorderLayout.NORTH);
getContentPane().add(imageLabel, BorderLayout.SOUTH);
javax.swing.Timer timer = new javax.swing.Timer(1000, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
timeLabel.setText( new Date().toString() );
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
String imageName = "timeLabel.jpg";
BufferedImage image = ScreenImage.createImage(timeLabel);
ScreenImage.writeImage(image, imageName);
// This works using ImageIO
// imageLabel.setIcon( new ImageIcon(ImageIO.read( new File(imageName) ) ) );
// Or you can flush the image
ImageIcon icon = new ImageIcon(imageName);
icon.getImage().flush();
imageLabel.setIcon( icon );
}
catch(Exception e)
{
System.out.println( e );
}
}
});
}
public static void main(String[] args)
{
ImageReload frame = new ImageReload();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
答案 1 :(得分:-1)
最终从框架中删除旧组件,并使用新图像读取标签
frame.remove(picLabel);
BufferedImage b = ImageIO.read(new File(attemptedFilePath));
picLabel = new JLabel(new ImageIcon(b));
GridBagConstraints c = new GridBagConstraints();
c.weightx = 0.5;
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(10,10,0,0);
c.gridwidth = 15;
c.gridheight = 15;
frame.getContentPane().add(picLabel, c);