本人小白在做游戏发现对空指针的疑问

芒果味丶 发布于 2016/05/26 15:56
阅读 222
收藏 0

public class GameFrame extends MyFrame {
 Image bg = GameUtil.getImg("img/bg.jpg");
 Plane p = new Plane("img/player.png",50, 50);
 KeyMonitor keymonitor1 = new KeyMonitor();

 class canvas extends JPanel {

  @Override
  protected void paintComponent(Graphics g) {
   super.paintComponent(g);
   g.drawImage(bg, 0, 0, null);
   p.draw(g);
  
  }

 }

 public static void main(String[] args) {
  GameFrame gameFrame = new GameFrame();
  gameFrame.launchFrame();

 }

 @Override
 public void launchFrame() {
  this.setContentPane(new canvas());
  super.launchFrame();

  this.addKeyListener(keymonitor1);

 }

 class KeyMonitor extends KeyAdapter {

  @Override
  public void keyPressed(KeyEvent e) {
   // TODO Auto-generated method stub
   p.press(e);

  }

  public void keyReleased(KeyEvent e) {
   p.Released(e);

  }

 }

}


import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;

public class Plane {
 double x, y;
 Image img=null;
 int speed = 10;
 boolean left, up, right, bottom;

 public Plane(String imgpath, int x, int y) {
  this.img = GameUtil.getImg(imgpath);
  this.x = x;
  this.y = y;

 }

 public void move() {

  if (left)
   x -= speed;

  if (up)
   y -= speed;

  if (right)
   x += speed;

  if (bottom)
   y += speed;

 }

 public void draw(Graphics g) {
  move();
  g.drawImage(img, (int) x, (int) y, null);
 }

 public void press(KeyEvent e) {
  int key = e.getKeyCode();
  switch (key) {
  case KeyEvent.VK_LEFT:
   left = true;
   break;
  case KeyEvent.VK_UP:
   up = true;
   break;
  case KeyEvent.VK_RIGHT:
   right = true;
   break;
  case KeyEvent.VK_DOWN:
   bottom = true;
   break;

  }
 }

 public void Released(KeyEvent e) {
  int key = e.getKeyCode();
  switch (key) {
  case KeyEvent.VK_LEFT:
   left = false;
   break;
  case KeyEvent.VK_UP:
   up = false;
   break;
  case KeyEvent.VK_RIGHT:
   right = false;
   break;
  case KeyEvent.VK_DOWN:
   bottom = false;
   break;
  }
 }

}


加载中
1
Shazi199
Shazi199
不贴出错信息别人怎么给你看。。
芒果味丶
芒果味丶
好了好了,可以帮我看看吗
芒果味丶
芒果味丶
哈哈,我的错,搞忘了3
1
xpbob
xpbob
应该是对象传递有问题
0
让往事随风
芒果味丶
芒果味丶
嗯嗯,我知道错误所在了,0
返回顶部
顶部