繁体   English   中英

从屏幕Java清除所有图形

[英]Clear all graphics from screen Java

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

我认为有一种常规方法可以做到这一点(我宁愿知道这种方法,而不必输入不必要的代码)。 提前致谢!

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

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

您应该始终调用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);
    }

"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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM