我想使用 JPanel 来显示游戏内容,因为我现在能够使用画布。这就是我所拥有的。
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
public class Game extends Canvas implements Runnable, KeyListener {
static boolean isRunning ;
public static boolean enter = false;
public static final int WIDTH = 640, HEIGHT = 480;
public static final String TITLE = "PA - CO";
private static Thread thread;
public static Player player;
public static Level level;
public static SpriteSheet spriteSheet;
public Game() {
Dimension dimension = new Dimension(Game.WIDTH, Game.HEIGHT);
setPreferredSize(dimension);
setMaximumSize(dimension);
setMinimumSize(dimension);
setVisible(true);
addKeyListener(this);
player = new Player(Game.WIDTH / 2, Game.HEIGHT / 2);
level = new Level("/map/map.png");
spriteSheet = new SpriteSheet("/sprites/sprites.png");
new Texture();
}
// ...other code related to keyListener and Thread
private void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;//not needed;
}
Graphics g = bs.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0, 0, Game.WIDTH, Game.HEIGHT);
player.render(g);
level.render(g);
g.dispose();
bs.show();
}
public static void main(String arg[]) {
new GameFrame();
}
}
我确实尝试过扩展 JPanel 类,但是我遇到了很多错误。其中之一是缓冲策略。我知道 JPanel 有自己的缓冲区,但我不确定如何实现该理论。