Issue with gif animation in Java swing

扶醉桌前 提交于 2019-12-13 02:23:20

问题


When I try to load a gif animation I am just getting an empty frame. Do you know what is wrong? The file is located within extras/loading.gif:

package an1;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class An1 {

 public static void main(String[] args){

    JFrame frame = new JFrame("Test");

    ImageIcon loading = new ImageIcon("extras/loading.gif");
    frame.add(new JLabel(loading, JLabel.CENTER));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);


}
}

I got loading.gif using this website http://spiffygif.com with the default settings. I just changed the name from gif.gif to loading.gif. Here it is:


回答1:


I'm running Ubuntu (Linux) so your code worked fine for me, which leads me to believe that this may be a file-separator issue with the filename. Are you running Windows? If so, try this:

ImageIcon loading = new ImageIcon("extras\\loading.gif");

The file-separator on Windows is "\" and on MAC/Linux is "/". Since "\" is an escape character in Java, you need to use two of them to actually get this to work.




回答2:


Run this source on your machine and check it works..

import java.net.*;
import javax.swing.*;

public class An1 {

    public static void main(String[] args) throws MalformedURLException {
        JFrame frame = new JFrame("Test");

        ImageIcon loading = new ImageIcon(
                new URL("http://i.stack.imgur.com/8IXqb.gif"));
        frame.add(new JLabel(loading, JLabel.CENTER));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
}

N.B. Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.



来源:https://stackoverflow.com/questions/36432480/issue-with-gif-animation-in-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!