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:
解决方案
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.