清除屏幕Java中的所有图形

时间:2013-10-25 23:30:06

标签: java graphics

我正在开展一场小型比赛,我想为失败设定条件。如果失败是真的,我希望清除屏幕上的所有图形,这样我就可以让屏幕上的一些输出文字。

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

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

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

2 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分: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);
    }
}

我还建议将变量defeat更改为defeated,并为Graphics对象提供更好的名称,例如我使用canvas