Java |前一帧不会消失

时间:2016-04-25 13:29:02

标签: java graphics drawing frames

我正在用java编写一个小游戏,但我有点问题。所有渲染的帧都保留在屏幕上,因此如果我移动图像,它只会继续渲染更多图像,但我希望我的图像在屏幕上移动。我做错了什么?

public void tick(){
    balk.tick();
}

public void render(){
    BufferStrategy bs = this.getBufferStrategy();

    if(bs==null){
        createBufferStrategy(2);
        return;
    }

    Font myFont = new Font ("Courier New", 1, 50);


    Graphics g = bs.getDrawGraphics();
    ///////////////////////////////

    g.drawImage(balk.getBalk(), balk.getX(), 900, this);
    g.setFont(myFont); 
    g.drawString("Score: " + 0, 50, 100);


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

}

public void init(){

    frame = new JFrame();

    WIDTH = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    HEIGHT = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
}

public static void main(String[] args){
    Game game = new Game();
    game.init();
    game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
    game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
    game.setMinimumSize(new Dimension(WIDTH, HEIGHT));

    frame.add(game);
    frame.setUndecorated(true);
    frame.setTitle("Ping Pong");
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setLayout(null);

    frame.addKeyListener(new KeyListener(){


        public void keyPressed(KeyEvent e) {

            int key = e.getKeyCode();

            if(key == KeyEvent.VK_A){
                balk.setVelX(-5);
            }

            if(key == KeyEvent.VK_D){
                balk.setVelX(5);
            }

        }


        public void keyReleased(KeyEvent e) {

            balk.setVelX(0);
        }

        public void keyTyped(KeyEvent arg0) {}

    });

    frame.setVisible(true);
    game.start();

}   
}

1 个答案:

答案 0 :(得分:0)

在使用填充窗口的fillRect绘制任何内容之前清除屏幕,颜色为您喜欢的颜色。

g.setColor(Color.black);
g.fillRect(0, 0, width, height);
//draw here

像这样的东西。