Reloaded file not change in java

85 views Asked by At

Im try to load image with file chooser, but when I updated image after loaded, and reload it, image is not change. It just show first time loaded. (I tryed not use filechooser)

Load-> change image -> Load -> image not change

Load-> change image ->Exit Program ->open program -> Load -> image change

How can I clear it?

Load Image

         int ret = chooser.showOpenDialog(null);    
         if(ret == JFileChooser.APPROVE_OPTION){
             String filePath = chooser.getSelectedFile().getPath();
             ImageIcon icon = new ImageIcon(filePath);
             main.ChangeImage(icon);
         }

Change Image

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();
}
1

There are 1 answers

0
Andrew Thompson On BEST ANSWER

Java tends to cache images.

If the images change during run-time, one way to fool the methods into reloading it is to read the bytes of the file yourself, form an input stream from them (using ByteArrayInputStream) and use the input stream in ImageIO.read(InputStream).

The reason this works is that if an URL or File is used to load the image, the toolkit uses the location as a key to cache it.


Other notes

public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    // ..

Should be:

public void paintComponent(Graphics g) {
    super.paintComponent(g); // paint the border and BG to avoid arttifacts!
    Graphics2D g2 = (Graphics2D) g;
    // ..