如何使用Canvas转换为使用JPanel?

时间:2018-01-17 14:18:57

标签: java swing canvas jpanel bufferstrategy

我想使用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有自己的缓冲区,但我不确定如何实现该理论。

0 个答案:

没有答案