我是 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 dimensiones
是关闭的,因为我无法在没有任何输出的情况下调整它)
当我尝试在方法中调用该方法image()
时,出现popupWindow()
此错误:
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 中调用 image 方法。我搞不清楚了。