repaint()错误。我的重绘方法只是闪烁屏幕

时间:2011-08-27 17:10:57

标签: java

我想我已经弄明白我的问题来自哪里了。当我评论出重绘()时,我得到了我通常会得到的东西。我使用矩形和2辆汽车在赛道上进行了筛选。显然没有什么看起来像是因为我注释掉了repaint()。如果我运行它,我的程序执行两件事之一。它要么不起作用,要么眨眼约3到5次然后停止。如果我注释掉sleep(),程序就会一直闪烁直到我退出。汽车像他们应该的那样移动。我不知道我做错了什么。如果您愿意,我还可以包含实际跟踪的代码。这只是一个漫长的过程,我认为我将其缩小到了这一点。

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

你走了:

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

}

2 个答案:

答案 0 :(得分:2)

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

另外,你应该考虑使用更好的控制你的线程,一段时间truc循环......很难停止。 :)

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

的问候,
  Stéphane

答案 1 :(得分:0)

你应该使用双缓冲来获得流畅的动画。

JComponent.setDoubleBuffered(boolean flag);