The problem is that when I resize an ImageIcon representing an animated gif and place it on a Jbutton, JToggelButton or JLabel, in some cases the image does not show or does not animate. More precicely, depending on the specific image file, the image shows always, most of the time or sometimes. Images which are susceptible to not showing often do not animate when showing. Moving over or clicking with the mouse on the AbstractButton instance while the frame is supposed to updated causes the image to disappear (even when viewing the non-animating image that sometimes appears). No errors are thrown.
Here some example code: (compiled with Java 6.0 compliance)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test
{
public static void main(String[] args)
{
new Test();
}
static final int IMAGES = 3;
JButton[] buttons = new JButton[IMAGES];
JButton toggleButton = new JButton("Toggle scaling");
boolean doScale = true;
public Test()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new GridLayout(1, IMAGES));
for (int i = 0; i < IMAGES; i++)
p.add(this.buttons[i] = new JButton());
f.add(p, BorderLayout.CENTER);
f.add(this.toggleButton, BorderLayout.SOUTH);
this.toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
Test.this.refresh();
}
});
f.setSize(600, 300);
f.setVisible(true);
this.refresh();
}
public void refresh()
{
this.doScale = !this.doScale;
for (int i = 0; i < IMAGES; i++)
{
ImageIcon image = new ImageIcon(i + ".gif");
if (this.doScale)
image = new ImageIcon(image.getImage().getScaledInstance(180, 180, Image.SCALE_AREA_AVERAGING));
image.setImageObserver(this.buttons);
this.buttons[i].setIcon(image);
this.buttons[i].setSelectedIcon(image);
this.buttons[i].setDisabledIcon(image);
this.buttons[i].setDisabledSelectedIcon(image);
this.buttons[i].setRolloverIcon(image);
this.buttons[i].setRolloverSelectedIcon(image);
this.buttons[i].setPressedIcon(image);
}
}
}
Download the gif images here:
http://djmadz.com/zombie/0.gif
http://djmadz.com/zombie/1.gif
http://djmadz.com/zombie/2.gif
When you press the "Toggle scaling"button it switches between unresized (properly working) and resized instances of three of my gif images. Notice that the left image almost never appears, the middle image always, and the right image most of the time. The right image seems to (almost) never animate. When you click on the left image (when visble) it disappears only when the backend is updating the animation (between those two frames with a long delay)
Why are the original ImageIcon and the resized ImageIcon behaving differently? Are they differently organized internally?
Is there any chance my way of resizing might be wrong?