首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >repaint()错误。我的repaint方法只会使屏幕闪烁

repaint()错误。我的repaint方法只会使屏幕闪烁
EN

Stack Overflow用户
提问于 2011-08-28 01:10:57
回答 2查看 480关注 0票数 2

我想我已经知道我的问题来自哪里了。当我注释掉repaint()时,我得到了我通常会得到的结果。我的屏幕上有一个赛道,这是我用矩形和2辆车创建的。显然,它看起来没有任何变化,因为我注释掉了repaint()。如果我按原样运行,我的程序会做两件事中的一件。它要么不工作,要么眨眼3到5次,然后就停止了。如果我注释掉sleep(),程序就会一直闪烁,直到我退出。汽车移动起来就像他们应该做的那样。我不知道我做错了什么。我也可以包括实际轨道的代码,如果你愿意。它只是太长了,我想我已经把范围缩小到这里了。

代码语言:javascript
复制
private class MoveTwo extends Thread{
    public void run(){
        //infinite loop
        while(true){
            try{
                repaint();//Refresh Screen
                if(playerTwoSpeed<=5) playerTwoSpeed+=.2;//slow acceleration

                playerTwo.y-=playerTwoSpeed;
                Thread.sleep(100);//Delay
            } catch(Exception e){
                break;//Stop if there is an error
            }
        }
    }
}

这就是了:

代码语言:javascript
复制
public void paint(Graphics g){
    super.paint(g);
    g.setColor(Color.DARK_GRAY);
    g.fillRect(0, 0, WIDTH, HEIGHT);

    //Turn Border green when we draw.
    g.setColor(Color.GREEN);

    //fill rectangles.
    g.fillRect(left.x, left.y, left.width, left.height);
    g.fillRect(right.x, right.y, right.width, right.height);
    g.fillRect(top.x, top.y, top.width, top.height);
    g.fillRect(bottom.x, bottom.y, bottom.width, bottom.height);
    g.fillRect(center.x, center.y, center.width, center.height);
    g.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
    g.fillRect(obstacle2.x, obstacle2.y, obstacle2.width, obstacle2.height);
    g.fillRect(obstacle3.x, obstacle3.y, obstacle3.width, obstacle3.height);
    g.fillRect(obstacle4.x, obstacle4.y, obstacle4.width, obstacle4.height);
    g.fillRect(obstacle5.x, obstacle5.y, obstacle5.width, obstacle5.height);

    g.setColor(Color.WHITE);//Change color to white.
    g.fillRect(outerStart.x, outerStart.y, outerStart.width, outerStart.height);
    g.fillRect(innerStart.x, innerStart.y, innerStart.width, innerStart.height);

    g.setColor(Color.YELLOW);
    g.fillRect(finish.x, finish.y, finish.width, finish.height);

    //Player one is blue
    g.setColor(Color.BLUE);
    g.fill3DRect(playerOne.x, playerOne.y, playerOne.width, playerOne.height, true);

    g.setColor(Color.RED);
    g.fill3DRect(playerTwo.x, playerTwo.y, playerTwo.width, playerTwo.height, true);

}
EN

回答 2

Stack Overflow用户

发布于 2011-08-28 01:14:58

您可能会使用来自JFrame子类的paint方法的覆盖。这会导致在许多操作系统上闪烁,因为JFrame是繁重的组件。解决方案是使用JComponent (通常是JPanel)的paintComponent方法的重写。代码将是相同的,但在Swing框架中集成会更流畅。

此外,你应该考虑对你的线程使用更好的控制,一个while truc循环is...difficult来停止。:)

您应该使用一个布尔标志和一个方法将其设置为true或false。

致以敬意,

Stéphane

票数 2
EN

Stack Overflow用户

发布于 2011-08-28 01:15:24

你应该使用双缓冲来获得平滑的动画效果。

代码语言:javascript
复制
JComponent.setDoubleBuffered(boolean flag);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7216058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档