我是一名Ap计算机科学课程的学生,而本课程的项目是创建一个自己选择的游戏。我正在制作一个吃豆人游戏。我们还没有太多地接触图形用户界面(GUI)方面,所以我对整个概念仍然很陌生,但这就是我目前为止的进展:
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class GameHandler extends JFrame{
JPanel jpanel = new JPanel();
Graphics g;
BufferedImage pacman;
int frame;
int direction;
int x, y;
//final int STEP = 2; If you want to change the speed at which pacman moves accross the screen;
public void popupWindow() {
setSize(400, 400);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame = 0;
direction = KeyEvent.VK_LEFT;
x = 300;
y = 300;
try {
pacman = ImageIO.read(new File("pacman.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
image();
}
public void keyPressed(KeyEvent e) {
direction = e.getKeyCode();
}
public void update() {
frame++;
if (frame > 2) {
frame = 0;
}
switch(direction) {
case KeyEvent.VK_LEFT:
x--;
break;
case KeyEvent.VK_RIGHT:
x++;
break;
case KeyEvent.VK_UP:
y--;
break;
case KeyEvent.VK_DOWN:
y++;
break;
}
}
public void image() {
super.paintComponents(g);
g.drawImage(pacman.getSubimage(frame*10, 0, 37, 30), x, y, null);
}
}
我的问题是我不能将这个图像输出到屏幕上(我知道我的 g.drawImage 维度
有点问题,因为我没有调整它而没有得到任何输出)
当我尝试在 popupWindow()
方法中调用 image()
方法时,我会得到以下错误:
Exception in thread "main" java.lang.NullPointerException
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:70)
at java.awt.Container.paintComponents(Container.java:1890)
at GameHandler.image(GameHandler.java:69)
at GameHandler.popupWindow(GameHandler.java:38)
at Main.main(Main.java:7)
我尝试在不同的位置和try/catch中调用图像方法,但我很迷惑。