0

我决定开始为我的图形了解 BufferStrategy。我不确定是否以静态形式使用我的 jframe 是导致这种情况的原因,但它看起来没问题。我错过了什么?

主.java

package Main;

import java.awt.Toolkit;


public class Main implements Runnable {

    private Thread gameThread;
    private Game game;
    private boolean running = false;
    public static ClientFrame frame;
    public static Toolkit kit;
    public static int WIDTH = 300, HEIGHT = WIDTH*16/9, SCALE = 3;

    public Main() {
        game = new Game();
        frame = new ClientFrame(game);
        kit = frame.getToolkit();

        frame.setVisible(true);
        start();
    }
    public synchronized void start() {
        running = true;
        gameThread = new Thread(this);

        gameThread.start();
    }
    public synchronized void stop() {
        running = false;

        gameThread.interrupt();
    }

    public void run() {
        long startTime = System.nanoTime();
        double nanoSec = 1000000000/60;
        double delta = 0;

        while(running) {
            long currentTime = System.nanoTime();
            delta += (currentTime - startTime)/nanoSec;

            while(delta >= 1) {
                game.update();

                delta--;
            }
            game.render();

            startTime = currentTime;
        }

    }

    public static void main(String[] args) {
        new Main();
    }

}

游戏.java

package Main;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.JPanel;

public class Game extends JPanel {

    Player player;

    int tileArea = 32;

    public Game() {
        player = new Player();
        setPreferredSize(new Dimension(Main.WIDTH*Main.SCALE, Main.HEIGHT*Main.SCALE));

    }

    public void update() {

    }

    public void render() {
        BufferStrategy bs = Main.frame.getBufferStrategy();
        if(bs == null)
            Main.frame.createBufferStrategy(3);

        Graphics g = bs.getDrawGraphics();

        player.paint(g);

        g.dispose();
        bs.show();
    }

}

我的 Player.java 只包含一种方法:

public void paint(Graphics g) {
    g.fillRect(25, 25, 50, 50);
}

错误:

Exception in thread "Thread-2" java.lang.NullPointerException
    at Main.Game.render(Game.java:30)
    at Main.Main.run(Main.java:52)
    at java.lang.Thread.run(Unknown Source)
4

2 回答 2

0

创建缓冲策略后,不要尝试获取它:

BufferStrategy bs = Main.frame.getBufferStrategy();
if(bs == null)
    Main.frame.createBufferStrategy(3);

//  if bs was null before, it still is null
Graphics g = bs.getDrawGraphics();

还要注意@MadProgrammer 的一点,即缓冲区策略属于不同的组件。如果您的意图是创建 AWT 游戏(我建议使用 swing),您可能应该使用Canvas及其createBufferStrategy().

于 2013-09-14T11:41:13.120 回答
0

尝试更换

    if(bs == null)
        Main.frame.createBufferStrategy(3);

    if (bs == null) {

        Main.frame.crcreateBufferStrategy(3);
        return;
    }
于 2014-02-23T19:42:28.550 回答