我刚刚开始进入图形,当我尝试获取图形时,我收到错误"运行: 线程"Thread-2"中的异常 java.lang.NullPointerException 在游戏开发。Display.render(Display.java:97) 在游戏开发。Display.run(Display.java:108) at java.lang.Thread.run(Thread.java:724)"而且我不知道发生了什么! 任何帮助将不胜感激。
//The display class for the game
//Crated: 10-30-2013
//Last Modified: 10-30-2013
package gamedev;
import gamedev.Graphics.Render;
import gamedev.Graphics.Screen;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Display extends Canvas implements Runnable {
public static final int GAMEWIDTH = 600;
public static final int GAMEHEIGHT = 600;
private static Thread thread;
private static boolean running = false;
private Render render;
private Screen screen;
private BufferedImage img;
private int[] pixels;
public static void main(String[] args) {
System.out.println("display.main");
Display gameWindow = new Display();
JFrame gameFrame = new JFrame();
gameFrame.add(gameWindow);
gameFrame.setResizable(false);
gameFrame.setVisible(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
gameFrame.setLocation(dim.width / 2 - gameFrame.getSize().width / 2, dim.height / 2 - gameFrame.getSize().height / 2);
gameFrame.setSize(GAMEWIDTH, GAMEHEIGHT);
gameFrame.setTitle("Game Frame");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameWindow.start();
}
public Display() {
System.out.println("display.Display");
screen = new Screen(GAMEWIDTH, GAMEHEIGHT);
img = new BufferedImage(GAMEWIDTH, GAMEHEIGHT, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
}
private void start() {
System.out.println("display.Started");
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private String stop() {
System.out.println("display.Stopped");
if (!running) {
System.out.println("running");
running = false;
try {
thread.join();
} catch (Exception e) {
System.exit(0);
return e.getStackTrace().toString();
}
return "Program Stopped";
} else {
return "Program Not Stopped";
}
}
private void tick() {
}
private void render() {
System.out.println("display.render");
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
}
for (int i = 0; i < GAMEWIDTH * GAMEHEIGHT; i++) {
pixels[i] = screen.PIXELS[i];
}
screen.Render();
Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, GAMEWIDTH, GAMEHEIGHT, null);
g.dispose();
bs.show();
}
@Override
public void run() {
System.out.println("display.run");
while (running) {
tick();
render();
}
}
}
更改以下内容:
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
}
自:
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
bs = this.getBufferStrategy();
}
问题是,如果bs
是null
,你创建一个缓冲区策略,但不为bs
分配任何东西。