NullPointerException带有getClass()。getResource的JApplet

时间:2012-04-12 05:18:42

标签: java swing nullpointerexception japplet

我想在JApplet中向JPanel添加一个图像(这样我就可以创建jar文件了),所以我使用了:

Image x = Toolkit.getDefaultToolkit().getImage(
  getClass().getResource("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));

但发生了java.lang.NullPointerException。我确定图像路径是正确的,因为我使用时applet运行正常:

Image image = ImageIO.read(new File("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));

例外情况:

    Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:830)
at sun.awt.SunToolkit.getImage(SunToolkit.java:887)
at applet$CustomPanel.paintComponent(applet.java:65)
at javax.swing.JComponent.paint(JComponent.java:1029)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JComponent.paintChildren(JComponent.java:862)
at javax.swing.JComponent.paint(JComponent.java:1038)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:567)

代码:

  import java.awt.BorderLayout;
  import java.awt.Color;
  import java.awt.Graphics;
  import java.awt.Image;
  import java.awt.Toolkit;
  import java.io.File;
  import java.io.IOException;

  import javax.imageio.ImageIO;
  import javax.swing.BorderFactory;
  import javax.swing.ImageIcon;
  import javax.swing.JApplet;
  import javax.swing.JButton;
  import javax.swing.JLabel;
  import javax.swing.JPanel;

  public class applet extends JApplet {
  public void init() {
    //Execute a job on the event-dispatching thread:
    //creating this applet's GUI.
    try {
        javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                createGUI();
            }
        });
    } catch (Exception e) {

        e.printStackTrace();
    }
}

  private void createGUI() {
    JPanel panel = new JPanel(new BorderLayout());
    JButton button = new JButton("CLICK ME");
    panel.add(button, BorderLayout.SOUTH);
    panel.add(new CustomPanel(), BorderLayout.CENTER);

    add(panel);
    }

public class CustomPanel extends JPanel{

    public void paintComponent(Graphics g) {

        Image image = null;
        try {
            image = ImageIO.read(new File("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Image x = Toolkit.getDefaultToolkit().getImage(getClass().getResource("D:/THANH_TAI LIEU/niet/hinhtu.jpg"));
        g.drawImage(x, 0, 0, null); 

    }   



}
}

可能是什么问题?

1 个答案:

答案 0 :(得分:2)

getClass().getResource()
仅适用于项目的类路径。
您需要将图像文件放在类路径上才能找到
其中ImageIO.read()可以读取params中传递的任何内容作为输入流。