2

我正在做一个小游戏,我想为失败设定条件。如果失败是真的,我希望清除屏幕上的所有图形,以便为屏幕上的一些输出文本让路。

我会假设有一种传统的方法可以做到这一点(我宁愿知道也不愿输入不必要的代码)。提前致谢!

到目前为止,这是我的代码:

public void paintComponent(Graphics g){
        if (!defeat){
            super.paintComponent(g);
            square.display(g);
            wall.display(g);
            for (Circle circle: circleArray){

                circle.display(g);
            }

        }else if(defeat){

            g.drawString("You have been defeated", 300, 300);
        }
4

2 回答 2

5

你应该总是打电话super.paintComponent(g);(除非你真的知道你在做什么)。

将该调用放在您的 if 语句之外。这个电话就是“清除屏幕”。像这样:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    if (!defeat){
        square.display(g);
        wall.display(g);
        for (Circle circle: circleArray){

            circle.display(g);
        }

    }else if(defeat){

        g.drawString("You have been defeated", 300, 300);
    }
于 2013-10-25T23:34:58.943 回答
0

"I want all the graphics on the screen to be cleared so I can make way for some output text on the screen",但您还希望每帧都清除屏幕,因此您基本上需要始终清除它,这意味着您应该放在super.paintComponent(g);任何 if 语句之外。
我推荐这段代码:(我已经清理了它并将框架移开)

public void paintComponent(Graphics g){
    super.paintComponent(g);
    if (defeat){
        g.drawString("You have been defeated", 300, 300);
    } else {
        square.display(g);
        wall.display(g);
        for (Circle circle: circleArray)
            circle.display(g);
    }
}

我还建议将变量更改defeatdefeated并给 Graphics 对象一个更好的名称,就像我使用canvas.

于 2013-10-25T23:49:56.053 回答