如何在Swing中刷新/重绘/重绘图形以用于游戏目的

时间:2017-05-30 11:13:34

标签: java swing user-interface graphics2d

我用Swing在Java中制作Snake游戏。我用Timer制作游戏循环。现在,在蛇的每一次动作之后,我都无法重新制作游戏板。

这是使用计时器执行的代码:

@Override
public void actionPerformed(ActionEvent e) {
    if(!isWon()) {
        inputDirection = inputManager.getCapturedDirection();
        try {
            snake.move(inputDirection);
        } catch (LosingMove losingMove) {
            gameLoop.stop();
            showGameOverDialog();
        }
    } else {
        gameLoop.stop();
        showWinDialog();
    }
    board.repaint();
}

所以我告诉我的电路板对象Board类扩展JPanel以在每次移动后重新绘制电路板。它的paintComponent()方法如下所示:

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    for (int row = 0; row < size.height; row++) {
        for (int col = 0; col < size.width; col++) {
            g2d.setColor(Color.WHITE);
            g2d.fill(fields[row][col].getGraphicRepresentation());
            g2d.setColor(Color.BLACK);
            g2d.draw(fields[row][col].getGraphicRepresentation());
            if (fields[row][col].getContent() instanceof Snake.SnakeNode) {
                g2d.setColor(Color.DARK_GRAY);
                g2d.fill(fields[row][col].getContent().getGraphicRepresentation());
                g2d.setColor(Color.BLACK);
                g2d.draw(fields[row][col].getContent().getGraphicRepresentation());
            } else if (fields[row][col].getContent() instanceof Apple) {
                g2d.setColor(Color.GREEN);
                g2d.fill(fields[row][col].getContent().getGraphicRepresentation());
                g2d.setColor(Color.BLACK);
                g2d.draw(fields[row][col].getContent().getGraphicRepresentation());
            }
        }
    }
}

graphicRepresentation只是一个Shape对象。

在调试器中执行此代码,但它不会影响我的游戏板窗口。游戏在后台运行,蛇正在改变它在游戏板阵列中的位置,但它没有正确重新绘制。所有显示的都是空场,一个蛇场,棋盘上的位置不正确(内存中的坐标是正确的),还有一个苹果场也在错误的位置,但内存中的值正确。

screen

如何以正确的方式做到这一点?

1 个答案:

答案 0 :(得分:0)

作为Snake游戏制作人,我了解一些潜在的错误,但是没有办法

  

一个苹果字段也在错误的位置,但在内存中具有正确的值。

如果你已经设置了正确的坐标,就会发生

您应该再次尝试检查Apple数组中SnakeNodefields的实例。