'Reload BufferImage Data when file changes
I been trying to figure out a way to re-load an image after it has suffer changes. For that I create a refresh button and my plan is, when clicking in this "reload" button re-load the original image so that we can see the new alterations that the file suffer(from an external software like W10 paint).
I tried quite a few things, one of them was using the flush method to attemp to reload the image, but to not avail.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageTest {
public static void main(String[] args) throws IOException {
new ApplicationView1();
}
static class ApplicationView1 extends JFrame{
JButton btnReload;
ImagePanel imagePanel;
public ApplicationView1() throws IOException {
initComponents();
addEventListeners();
setTitle("Pokemon Tile Creator");
setPreferredSize(new Dimension(200, 360));
setResizable(false);
setVisible(true);
pack();
}
private void initComponents() throws IOException {
btnReload = new JButton("Reload");
BufferedImage bufferedImage = ImageIO.read(new File("C:/Florest_PixelArt.png"));
imagePanel = new ImagePanel(bufferedImage);
setLayout(new BorderLayout());
add(btnReload, BorderLayout.PAGE_START);
add(imagePanel, BorderLayout.CENTER);
}
private void addEventListeners() {
btnReload.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
imagePanel.image = ImageIO.read(new File("C:/Florest_PixelArt.png"));
repaint();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
});
}
}
static class ImagePanel extends JPanel{
public BufferedImage image;
public ImagePanel(BufferedImage image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

