Quantcast
Channel: WP快站
Viewing all articles
Browse latest Browse all 233

Gif no longer animated after replacing with JLabel's setIcon method

$
0
0

I am still very new to Java and programming in general. I am trying to display a GIF using Swing and the following code:

    JPanel contentPane;    JLabel imageLabel = new JLabel();    public FrostyCanvas(String imageName) {        try {            setDefaultCloseOperation(EXIT_ON_CLOSE);            contentPane = (JPanel) getContentPane();            contentPane.setLayout(new BorderLayout());            setSize(new Dimension(1600, 900));            setTitle("FrostySpirit v1.1.1 (Beta) - FrostyCanvas");            // add the image label            ImageIcon ii = new ImageIcon(this.getClass().getResource(imageName));            imageLabel.setIcon(ii);            contentPane.add(imageLabel, java.awt.BorderLayout.CENTER);            // display target GIF            this.setLocationRelativeTo(null);            this.setVisible(true);        } catch (Exception exception) {            exception.printStackTrace();        }    }

The method call is the following: (in a different class)

FrostyCanvas FC = new FrostyCanvas("old.gif");

The GIF is animated at this point. I then try to replace the GIF with another one using the following method: (in the same class as ForstyCanvas(String imageName))

public void changeGif(String imageName) throws IOException    {        Icon icon; File file;        file = new File(imageName);        icon = new ImageIcon(ImageIO.read(file));        imageLabel.setIcon(icon);    }

I call the method above in a different class using the following code:

FC.changeGif("D:\\new.gif")

The image is successfully replaced. However, now it only shows the very first frame of new.gif and is no longer animated. How can I make the new GIF move?


Viewing all articles
Browse latest Browse all 233

Trending Articles