显示动画GIF

Sam*_*Sol 33 java image gif animated-gif

如何在Java应用程序中显示动画GIF?

sta*_*ker 31

使用swing你可以简单地使用JLabel

 public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("<URL to your Animated GIF>");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);

        JFrame f = new JFrame("Animation");
        f.getContentPane().add(label);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
Run Code Online (Sandbox Code Playgroud)

  • 出于某种原因,如果你的`ImageIcon`对象有这样的东西`Icon icon = new ImageIcon(ImageIO.read(getClass().getResourceAsStream("iconasresource.gif")));`你的GIF不会被动画 (9认同)
  • 实际上,使用ImageIO.read创建ImageIcon不会出于某种原因为gif设置动画.也许很明显,但你可以通过以下方式获取资源的URL:`URL url = getClass().getResource("/ img.gif");`. (5认同)
  • 这是一个可怕的 API... 试图弄清楚为什么 GIF 没有动画。在我看到关于“ImageIO”的评论之前,我在网上找不到任何东西。逆天。 (3认同)

Sco*_*law 6

为了加载存储在源包中的动画GIF(在源代码中),这对我有用:

URL url = MyClass.class.getResource("/res/images/animated.gif");
ImageIcon imageIcon = new ImageIcon(url);
JLabel label = new JLabel(imageIcon);
Run Code Online (Sandbox Code Playgroud)

  • 这正是对我不起作用的。图像已加载,但仅显示第一帧,没有动画。 (2认同)

小智 5

这项工作对我来说!

public void showLoader(){
        URL url = this.getClass().getResource("images/ajax-loader.gif");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);
        frameLoader.setUndecorated(true);
        frameLoader.getContentPane().add(label);
        frameLoader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frameLoader.pack();
        frameLoader.setLocationRelativeTo(null);
        frameLoader.setVisible(true);
    }
Run Code Online (Sandbox Code Playgroud)