线程“main”java.lang.NullPointerException中的异常

时间:2013-11-04 21:02:30

标签: java netbeans

嗨,我是新手到这里和java所以我相信这将是一个我忽略的简单事情,感谢任何帮助我的主类的代码在这里,错误代码在底部

package GameScreen;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;


public class GameScreen extends JFrame
implements Runnable, KeyListener
{
private Thread animation = new Thread(this);
private Container back = getContentPane();
private AniScreen aniscreen = new AniScreen();

public GameScreen()
{
   super("moving image");
   setBounds(20,20,1024,768);
   back.add (aniscreen, BorderLayout.CENTER);
   animation.start();
   addKeyListener(this);

   setVisible (true);

}
   /**
    * @param args the command line arguments
    */
   public static void main(String[] args)
   {
      GameScreen gameScreen = new GameScreen();
   }

   @Override
   public void run()
   {
      while (true)
      {
         aniscreen.repaint();
         try
         {
            Thread.sleep(30);
         }
         catch(InterruptedException ex)
            {

            }
      }

   }

   @Override
   public void keyTyped(KeyEvent e)
   {
         }

   @Override
   public void keyPressed(KeyEvent e)
   {
      if (e.getKeyCode()==KeyEvent.VK_DOWN)
      {
        aniscreen.moveplayer(0,50);
      }
       if (e.getKeyCode()==KeyEvent.VK_UP)
      {
        aniscreen.moveplayer(0,-50);

      }

   }

   @Override
   public void keyReleased(KeyEvent e)
   {
      aniscreen.moveplayer(0,0);
   }
}

这是错误代码:

    Exception in thread "main" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:205)
    at GameScreen.AniScreen.<init>(AniScreen.java:15)
    at GameScreen.GameScreen.<init>(GameScreen.java:15)
    at GameScreen.GameScreen.main(GameScreen.java:33)
Java Result: 1

这是aniscreen类

package GameScreen;

import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JComponent;


public class AniScreen extends JComponent
{
private int x = 0;
private int y = 0;
private int xMovement;
private int yMovement;

   private ImageIcon CINEMA = new ImageIcon (getClass().getResource ("CINEMA.jpg"));
   private ImageIcon survivor = new ImageIcon(getClass().getResource("survivor.jpg"));
   @Override
   public void paint (Graphics g)
   {
      x = x + xMovement;
      y = y + yMovement;
      g.drawImage(CINEMA.getImage(),x,y,100,100,null);
      g.drawImage(survivor.getImage(),x,y,100,100,null); 
   }
public void moveplayer (int xmov, int ymov)
{
   xMovement = xmov;
   yMovement = ymov;
}

}

1 个答案:

答案 0 :(得分:0)

问题是(最有可能)发生在这里:

   private ImageIcon CINEMA = 
       new ImageIcon (getClass().getResource ("CINEMA.jpg"));

或在这里:

   private ImageIcon survivor = 
       new ImageIcon(getClass().getResource("survivor.jpg"));

您正在使用ImageIcon引用调用null构造函数。这种情况正在发生,因为getResource无法找到您已命名的资源。发生这种情况时,它会返回null而不是抛出异常。 javadoc解释了这一点。