Using ImageIcon with a temporary image.
807588Aug 10 2009 — edited Aug 10 2009I am attempting to make a menu that allows you to go through directories and look at files. Currently I am trying to set allow a user to click a JButton of the file to open the image up in a
JLabel as an ImageIcon. I set the program so that it would take an instance of the image, and create a resized version of it as a temporary file. The problem here is that even when I delete or overwrite the previous image, original image will still be displayed. I have tried using if(fileIcon.getImageLoadStatus() == MediaTracker.COMPLETE) and setting a while loop to check whether the time between writing the image and loading it was a problem, but the results are the same regardless of time.
This is what I am currently using to re-size and get a new image:
public void showFile(int number) throws IOException{
frame = new JFrame();
frame.setSize(600,400);
fileIcon = null;
GridLayout layout = new GridLayout();
String tempFile = "C:\\Users\\t5g54gwg\\Pictures\\TempFile.jpg";
String fileName = allFiles[number].getPath();
GetImage getImage = new GetImage(fileName,400,300,true);
fileIcon = new ImageIcon(tempFile);
System.out.println(fileIcon);
JLabel label = new JLabel();
label.setIcon(fileIcon);
label.setLayout(layout);
label.setLocation(400,200);
label.setVisible(true);
frame.setLayout(layout);
frame.add(label);
frame.setLocation(200,200);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void scaleIcon(String source, int width, int height) throws IOException {
BufferedImage sourceIcon = ImageIO.read(new File(source));
BufferedImage finalIcon = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = finalIcon.createGraphics();
AffineTransform transform = AffineTransform.getScaleInstance((double)width/sourceIcon.getWidth(),(double)height/sourceIcon.getHeight());
g.drawRenderedImage(sourceIcon,transform);
File fileName = new File("C:\\Users\\t5g54gwg\\Pictures\\TempFile.jpg");
boolean success = fileName.delete();
ImageIO.write(finalIcon,"JPG",new File("C:\\Users\\t5g54gwg\\Pictures\\TempFile.jpg"));
}