0

I want to use JPanel to display the Game content as of now I was able to use canvas. This is what I have.

    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();
        }
    }

I did try extending the JPanel class however I got many errors. One of which is with the bufferstrategy. I know that JPanel has its own buffer but I'm not sure how to implement the theory.

  • _"got many errors"_ Maybe you should try posting the specific errors and the code that caused them? How were you trying to set the buffering method? – phflack Jan 17 '18 at 14:29
  • Override the `paintComponent(Graphics)` method in your `JPanel` subclass and implement your drawing logic there. Call `repaint()` on your `JPanel` when you wish to redraw. There shouldn't be a need to use `BufferStrategy`. – d.j.brown Jan 17 '18 at 14:30
  • @phfalck the errors caused by the BufferStrategy are clear. Its because JPanel does not need a BufferStrategy. This is clear, posting these errors are pointless. – Michael Gonzalez Jan 17 '18 at 14:42

0 Answers0