我有一张在程序开始时从文件夹中读取的图像。程序会从网上下载一张新图片,并覆盖旧图片,相同的文件路径和相同的名称,但显示的图像是旧图像。当我退出并重新加载程序时,会显示新图像。我知道图像没有改变,因为我还尝试从文件路径创建一个新的 ImageIcon 并在下载后在 JDialog 中显示它,它仍然是旧图像。有任何想法吗?
问问题
591 次
2 回答
4
但是只有 jdialog 才能正确显示。即使我调用了 frame.validate(),原始帧仍然显示旧图像;frame.repaint();
将图像读入内存不会导致组件引用新图像。您仍然需要将图标添加到使用旧图像的任何组件中。
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);
}
}
于 2013-05-31T22:14:06.350 回答
-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);
于 2013-05-31T22:23:10.850 回答