0

我正在为一个类编写一个小程序,并认为代码看起来正确,我在小程序启动时收到一个空指针异常。任何帮助将不胜感激。

错误信息:

java.lang.NullPointerException
at sun.applet.AppletAudioClip.(AppletAudioClip.java:65)
at java.applet.Applet.newAudioClip(Applet.java:311)
at 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)
at 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。线程运行(线程.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);
        }
  }
}
4

1 回答 1

0

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

  • Lab5b.class
  • 声音的/
    • 我们.mid
于 2013-04-02T22:11:12.847 回答