gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:46:16 24 4
gpt4 key购买 nike

我想我已经弄清楚我的问题出在哪里了。当我注释掉 repaint() 时,我得到了我通常会得到的结果。我用矩形和 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);

}

最佳答案

您可能使用 JFrame 子类中的 paint 方法的重写。由于 JFrame 是重型组件,因此这会导致许多操作系统出现问题。解决方案是使用 JComponent(通常是 JPanel)的 paintComponent 方法的重写。代码会相同,但会更顺利地集成到 Swing 框架中。

此外,您应该考虑更好地控制线程,while truc 循环……很难停止。 :)

您应该使用 boolean 标志和方法将其设置为真或假。

问候,
斯蒂芬

关于java - 重绘()错误。我的重绘方法只是闪烁屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7216058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com