启动时JApplet空指针异常

时间:2013-04-02 21:49:24

标签: java

我正在编写一个类的applet,并认为代码看起来正确,我在applet start上得到一个空指针异常。任何帮助将不胜感激。

错误讯息:

显示java.lang.NullPointerException
        在sun.applet.AppletAudioClip。(AppletAudioClip.java:65)
        在java.applet.Applet.newAudioClip(Applet.java:311)
        在Lab5b。(Lab5b.java:14)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct orAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC onstructorAccessorImpl.java:45)
        在java.lang.reflect.Constructor.newInstance(Constructor.java:525)
        在java.lang.Class.newInstance0(Class.java:372)
        在java.lang.Class.newInstance(Class.java:325)
        在sun.applet.AppletPanel.createApplet(AppletPanel.java:795)
        在sun.applet.AppletPanel.runLoader(AppletPanel.java:724)
        在sun.applet.AppletPanel.run(AppletPanel.java:378)
        在java.lang.Thread.run(Thread.java:722)

代码:

import javax.swing.*;
import java.awt.event.*;
import java.net.URL;
import java.applet.*;
import java.awt.*;

public class Lab5b extends JApplet {
  private AudioClip audioClip;

  public Lab5b() {
    add(new ImagePanel());

    URL urlForAudio = getClass().getResource("audio/us.mid");
    audioClip = Applet.newAudioClip(urlForAudio);
    audioClip.loop();
  }

  public void start() {
    if (audioClip != null) audioClip.loop();
  }

  public void stop() {
    if (audioClip != null) audioClip.stop();
  }

  /** Main method */
  public static void main(String[] args) {
    // Create a frame
    JFrame frame = new JFrame("Lab 5");

    // Create an instance of the applet
    Lab5b applet = new Lab5b();
    applet.init();

    // Add the applet instance to the frame
    frame.add(applet, java.awt.BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Display the frame
    frame.setSize(200, 660);
    frame.setVisible(true);
  }
}

class ImagePanel extends JPanel {
  private ImageIcon imageIcon = new ImageIcon("image/us.gif");
  private Image image = imageIcon.getImage();
  private int y = 550;

  public ImagePanel() {
        Timer timer = new Timer(120, new TimerListener());
        timer.start();
    }

    class TimerListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            increaseY();
        }
    }


  public void increaseY() {
        if (y > 0) {
            y--;
            repaint();
        }
    }

  /** Draw image on the panel */
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (image != null) {
      g.fillRect(0, 0, 10, 660);
      g.drawImage(image, 11, y, 160, 84, this);
        }
  }
}

1 个答案:

答案 0 :(得分:0)

当无法找到资源时,getResource方法返回null,这会使AppletAudioClip构造函数抛出异常。确保us.mid位于名为audio的目录中,该目录与Lab5b.class位于同一目录中:

  • Lab5b.class
  • 音频/
    • us.mid