This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12个答案)
4年前关闭。
我试图在JFrame上绘制一个简单的矩形,但是当我尝试绘制它时,它给了我NullPointerException。我找不到问题,因为它是我已经使用的代码之一。 Null对象是我从超类获得的Graphics对象。有人可以帮我弄这个吗?
错误:
完整代码:
(12个答案)
4年前关闭。
我试图在JFrame上绘制一个简单的矩形,但是当我尝试绘制它时,它给了我NullPointerException。我找不到问题,因为它是我已经使用的代码之一。 Null对象是我从超类获得的Graphics对象。有人可以帮我弄这个吗?
错误:
Exception in thread "Thread-2" java.lang.NullPointerException
at com.daansander.game.Game.render(Game.java:83)
at com.daansander.game.Game.run(Game.java:76)
at java.lang.Thread.run(Thread.java:745)
完整代码:
package com.daansander.game;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
/**
* Created by Daan on 12-9-2015.
*/
public class Game extends Canvas implements Runnable {
public static final int WIDTH = 500;
public static final int HEIGHT = WIDTH / 12 * 9;
public static final int SCALE = 2;
public static final String NAME = "2DGame";
private JFrame frame;
private volatile boolean running;
public Game() {
setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
frame = new JFrame(NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this, BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game().start();
}
public synchronized void start() {
running = true;
new Thread(this).start();
}
public synchronized void stop() {
}
@Override
public void run() {
long lastTime = System.currentTimeMillis();
long current;
long delta = 0;
int frames = 0;
// int ticks = 0;
while (running) {
current = System.currentTimeMillis();
delta += current - lastTime;
lastTime = current;
frames++;
if (delta > 1000) {
delta -= 1000;
System.out.println("FRAMES " + frames);
frames = 0;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
render();
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
Graphics g = bs.getDrawGraphics(); // <----- Line of error
// g.setColor(Color.black);
// g.drawRect(0, 0, 5, 5);
//
// g.dispose();
// bs.show();
}
public void tick() {
}
public void init() {
}
}
最佳答案
getBufferStrategy()
返回null。作为fabian linked to above:
公共BufferStrategy getBufferStrategy()
返回此组件使用的BufferStrategy。如果尚未创建或已废弃BufferStrategy,则此方法将返回null。
You need to create a BufferStrategy
first.
10-08 15:57