重新加载的文件在 java 中没有变化
Reloaded file not change in java
我尝试使用文件选择器加载图像,
但是当我在加载后更新图像并重新加载时,图像没有改变。它只显示第一次加载。
(我试过不使用文件选择器)
加载-> 更改图像-> 加载-> 图像不变
加载->更改图像->退出程序->打开程序->加载->图像更改
如何清除它?
加载图片
int ret = chooser.showOpenDialog(null);
if(ret == JFileChooser.APPROVE_OPTION){
String filePath = chooser.getSelectedFile().getPath();
ImageIcon icon = new ImageIcon(filePath);
main.ChangeImage(icon);
}
更改图像
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image.getImage(), 0, 0, this);
}
public void ChangeImage(ImageIcon img) {
image = img;
origin_image = image;
origin_height = image.getIconHeight();
origin_width = image.getIconWidth();
this.setBounds(0, 0, image.getImage().getWidth(null), image.getImage()
.getHeight(null));
repaint();
}
Java倾向于缓存图片。
如果图像在 运行 时间内发生变化,一种欺骗方法重新加载它的方法是自己读取文件的字节,从中形成一个输入流(使用 ByteArrayInputStream
) 并使用 ImageIO.read(InputStream)
.
中的输入流
这样做的原因是,如果使用 URL
或 File
加载图像,工具包会使用该位置作为缓存它的键。
其他说明
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// ..
应该是:
public void paintComponent(Graphics g) {
super.paintComponent(g); // paint the border and BG to avoid arttifacts!
Graphics2D g2 = (Graphics2D) g;
// ..
我尝试使用文件选择器加载图像, 但是当我在加载后更新图像并重新加载时,图像没有改变。它只显示第一次加载。 (我试过不使用文件选择器)
加载-> 更改图像-> 加载-> 图像不变
加载->更改图像->退出程序->打开程序->加载->图像更改
如何清除它?
加载图片
int ret = chooser.showOpenDialog(null);
if(ret == JFileChooser.APPROVE_OPTION){
String filePath = chooser.getSelectedFile().getPath();
ImageIcon icon = new ImageIcon(filePath);
main.ChangeImage(icon);
}
更改图像
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image.getImage(), 0, 0, this);
}
public void ChangeImage(ImageIcon img) {
image = img;
origin_image = image;
origin_height = image.getIconHeight();
origin_width = image.getIconWidth();
this.setBounds(0, 0, image.getImage().getWidth(null), image.getImage()
.getHeight(null));
repaint();
}
Java倾向于缓存图片。
如果图像在 运行 时间内发生变化,一种欺骗方法重新加载它的方法是自己读取文件的字节,从中形成一个输入流(使用 ByteArrayInputStream
) 并使用 ImageIO.read(InputStream)
.
这样做的原因是,如果使用 URL
或 File
加载图像,工具包会使用该位置作为缓存它的键。
其他说明
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// ..
应该是:
public void paintComponent(Graphics g) {
super.paintComponent(g); // paint the border and BG to avoid arttifacts!
Graphics2D g2 = (Graphics2D) g;
// ..