简体   繁体   中英

Loading image from .jar, Null Pointer Exception

I'm running this code, and it's returning the following stack trace:

Uncaught error fetching image:
java.lang.NullPointerException
at sun.awt.image.URLImageSource.getConnection(URLImageSource.java:115)
at sun.awt.image.URLImageSource.getDecoder(URLImageSource.java:125)
at sun.awt.image.InputStreamImageSource.doFetch(InputStreamImageSource.java:263)
at sun.awt.image.ImageFetcher.fetchloop(ImageFetcher.java:205)
at sun.awt.image.ImageFetcher.run(ImageFetcher.java:169)

I'm not sure where I made the mistake to output a Null Pointer exception. Tips on how to fix this?

import java.awt.BorderLayout;  
import java.awt.EventQueue;  
import java.awt.Graphics;  
import java.awt.Image;  
import java.awt.Toolkit;  
import javax.swing.JFrame;  
import javax.swing.JPanel;  
import javax.swing.border.EmptyBorder;  

public class MyFrame extends JFrame {  
     private JPanel contentPane;  

     public static void main(String[] args) {  
          EventQueue.invokeLater(new Runnable() {  
              public void run() {  
                    try {  
                         MyFrame frame = new MyFrame();  
              frame.setVisible(true);  
               } catch (Exception e) {  
                         e.printStackTrace();  
                   }  
               }  
        });  
     }   
   public MyFrame() {  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        setBounds(100, 100, 450, 300);  
        contentPane = new JPanel() {  
             public void paintComponent(Graphics g) {  
                  Image img = Toolkit.getDefaultToolkit().getImage(  
                           MyFrame.class.getResource("/images/Ella and Louis_front.jpg"));  
                 g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);  
             }  
        };  
       contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));  
        contentPane.setLayout(new BorderLayout(0, 0));  
        setContentPane(contentPane);         }  

}

when getting a resource: MyFrame.class.getResource("/images/Ella and Louis_front.jpg") it returns a null , I suggest doing a check: I suggest doing a check:

URL url = MyFrame.class.getResource("/images/Ella and Louis_front.jpg")
if (url != null) {
    Image img = Toolkit.getDefaultToolkit().getImage(url);
}

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