'Stale' image reference is retained by JFrame desktop app--latest image won't display
Joined: Apr 08, 2003
In a JFrame desktop application I have written, a user clicks a button to capture and save an image to a file. The image capture is achieved by activating third party software via an exec() call on a process generated through ProcessBuilder. The captured JPEG image is then displayed in a JPanel contained within the JFrame. This JPanel loads and displays the image by use of an ImageIcon and JLabel.
The display works perfectly on initial image capture. A JPanel is constructed for the captured image and it faithfully displays this image.
But if, for example, I capture an image a second time, and the application saves to the same filename as used in the first capture, the application continues to display the first image, not the most recently captured one. This is true even though I call removeAll() on the JFrame and construct a new JPanel to hold the new image. I have verified that the image capture component of the application works correctly--that the image file, if opened, represents the second, most recently captured image.
I have tried several strategies to get the JFrame to flush the old and to display the latest image. These including constructing a new JPanel and adding to the JFrame after (1) calling removeAll() on the JFrame; (2) calling removeAll on the existing JPanel before setting that JPanel to null; (3) getting a reference to the image via imageIcon.getImage(), storing the image reference in an instance of MediaTracker, then later calling removeImage() on the tracker instance and finally flush() on the image reference.
But somehow the application still displays the old image, not the new one.
Any ideas on how to get the JFrame to release its hold on the old, 'stale' image reference and to display the newest one?
Thanks in advance!
Joined: Jun 13, 2009
a user clicks a button to capture and save an image to a file.... The captured JPEG image is then displayed in a JPanel
An easier solution would be to:
a) create an image
b) use the image to update the panel
c) save the image to file for futhre reference.
This way you don't have problems with the caching of the image.
However to answer the question there are a couple of ways to solve this:
a) use ImageIO to read the new image, or
b) use image.flush() to force the loading of the image.
Here is my little demo program. It uses the Screen Image class. The bottom label is a copy of the top label that is continuously updated by a Timer.