Reputation: 23
I have an image that is read from a folder at the start of the program. The program will download a new image from the internet and overwrite the old image, same filepath and same name, but the image displayed is the old image. When I exit and reload the program, the new image is displayed. I know that the image isn't changing because I also tried to create a new ImageIcon from the filepath and display it in a JDialog after downloading and it's still the old image. Any ideas?
Upvotes: 0
Views: 651
Reputation: 23
ended up deleting the old component from the frame, and readding the label with the new image
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);
Upvotes: -1
Reputation: 324207
however it's only the jdialog that displays correctly. the original frame still shows the old image even though i've called frame.validate(); frame.repaint();
Reading an image into memory does not cause the component to reference the new image. You still need to add the Icon to any component that used the old image.
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);
}
}
Upvotes: 4