简体   繁体   中英

java.lang.NullPointerException when trying to display a ,gif file?

Well basically I tried to display a .gif using a url but it's given me a null pointer exception and I'm not really sure why since my url is correct and there's no other problems with my code(At least none that I can see).

   import javax.swing.*;
   import java.net.*;
public class image {

public image() {

}

public static void main(String[] args) {


    URL url = image.class.getResource("<http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif>");
    ImageIcon imageIcon = new ImageIcon(url);
    JLabel label = new JLabel(imageIcon);
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    panel.add(label);
    frame.add(panel);
    frame.setTitle("Title");  
    frame.setSize(700,500);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);


         }

    }
URL url = image.class.getResource("<http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif>");

is not how you reference an image from a web resources. You would use this method to load resources that are embedded within your application (within the context of the applications classpath)

URL url = new URL("http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif");

would probably work better...

Remember, that downloading and loading the image may take some time, you may want to use a MediaTracker to track the progress, this would allow you to provide feedback to the user and know when to update the screen with the image once it's available, for example.

Before anyone asks, I choose not to use ImageIO to load an animated gif , because that is just a lot more work (as demonstrated here - not for the faint hearted). In this case, the MediaTracker could be used to check for errors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM