我收到一个错误:Graphics g上的java.lang.NullPointerException。 这是我的代码:
package main;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class main implements Runnable {
public static final int WIDTH = 1024;
public static final int HEIGHT = 1024;
public static final String TITLE = "platformer";
public boolean running = false;
static main home = new main();
public Graphics g;
public static Canvas canvas = new Canvas();
public static void main(String[] args) {
home.display();
home.start();
}
public void display(){
JFrame frame = new JFrame(TITLE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
canvas.setPreferredSize(new Dimension(WIDTH, HEIGHT));
frame.add(canvas);
}
BufferStrategy bs;
public void render(){
bs = main.getCanvas().getBufferStrategy();
if(bs == null){
main.getCanvas().createBufferStrategy(3);
}
g = bs.getDrawGraphics();
g.fillRect(0, 0, WIDTH, HEIGHT);
g.dispose();
bs.show();
}
public void tick(){
}
public void run(){
long lastTime = System.nanoTime();
final double amountofticks = 60;
double ns = 1000000000/amountofticks;
double delta = 0;
double time = 0;
int frames = 0;
while(running){
long now = System.nanoTime();
delta += (now-lastTime)/ns;
time += (now-lastTime);
lastTime = now;
if(delta>=1){
home.tick();
home.render();
delta--;
frames++;
}
if(time>1000000000){
System.out.println(frames);
time = 0;
frames = 0;
}
}
stop();
}
private Thread thread;
public void start(){
running = true;
thread = new Thread(this);
thread.start();
}
public static Canvas getCanvas(){
return canvas;
}
public void stop(){
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我收到错误消息: 线程“Thread-2”中的异常java.lang.NullPointerException 在main.main.render(main.java:37) 在main.main.run(main.java:59) 在java.lang.Thread.run(未知来源) 第37行是 g = bs.getDrawGraphics(); 我认为图形由于某种原因是空的。 我试图长时间制作这段代码
答案 0 :(得分:1)
更改行
main.getCanvas().createBufferStrategy(3);
到
bs = main.getCanvas().createBufferStrategy(3);