我正在尝试显示一个黑色的窗口,但我一直在第72和43行得到空指针异常。这是我的视频游戏的基础,我一直在使用教程来帮助我,因为我是java的新手。它起初是一个无法访问的代码错误,但我通过返回修复了,然后这个问题立即出现了任何帮助? 代码:
package com.tyler99b.platformer.window;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable
{
private static final long serialVersionUID = 506346024107270629L;
private boolean running = false;
private Thread thread;
public synchronized void start(){
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
public void run()
{
long lastTime = System.nanoTime();
double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
long timer = System.currentTimeMillis();
int updates = 0;
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
while(delta >= 1){
tick();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000){
timer += 1000;
System.out.println("FPS: " + frames + " TICKS: " + updates);
frames = 0;
updates = 0;
}
}
}
private void tick()
{
}
private void render()
{
BufferStrategy bs = this.getBufferStrategy();
if(bs == null);
{
this.createBufferStrategy(3);
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0,0, getWidth(), getHeight());
g.dispose();
bs.show();
}
public static void main(String args[]){
new Window(800,600, "Platformer Prototype", new Game ());
}
}
答案 0 :(得分:2)
如果它是null,那么你似乎正在使用创建某些东西的常见模式。但是,在这里你将bs设置为getBufferStrategy(),如果它为null,则创建它。让我们假设功能成功。 bs仍为空
BufferStrategy bs = this.getBufferStrategy();
if (bs == null){
this.createBufferStrategy(3);
//bs still null
}
您需要重新尝试将bs设置为等于
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
bs = this.getBufferStrategy();
}
所有这些都假定createBufferStrategy不会失败。如果可以,你必须决定在这种情况下该做什么
你的if语句也有停留;在里面。这使得它成为一个空的if语句
答案 1 :(得分:0)
在处理bs == null。
时,你肯定错过了其他人 if(bs == null) //there should not be a semi-colon here;
{
this.createBufferStrategy(3);
}
else
{
Graphics g = bs.getDrawGraphics();
g.setColor(Color.black);
g.fillRect(0,0, getWidth(), getHeight());
g.dispose();
bs.show();
}