我有一份工作要为学校做。有一个窗口,里面有鸽子,通过点击鼠标我们放置一些鸽子必须吃的食物。为了简单起见,我使用 swing 画一些填充圆形作为食物,填充方形作为鸽子。 Pigeons 和 Foods 是具有 PigeonShape 或 FoodShape 对象(JPanel)的线程。
当我放置食物时,鸽子会朝正确的方向移动。问题是,因为我使用 swing,所以每次更改 PigeonShape 的位置时都必须重新绘制 PigeonShape。这是 Pigeon.java 中的代码:
run()
:
public void run(){
while(true){
try {
sleep(25);
this.observe(); //just to check what is the closest piece of Food, we don't care here
this.move();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
还有move()
:
private void move(){
//If there is available food, the Pigeon has to move to it
if(this.closest != null){
/*
* some calculations for the move
* coordonates are stored in xPigeon et yPigeon that are integers
*/
//it makes the PigeonShape disappear because the background is white too
this.draw.setColor(Color.WHITE); //(1)
this.draw.repaint(); //(2)
//it changes coordinates of the Pigeon
//each time those functions are called, it call the same function for this.draw (the PigeonShape)
this.setPosX(xPigeon);
this.setPosY(yPigeon);
//it makes the PigeonShape reappear
this.draw.setColor(CURIOUS); //(3)
this.draw.repaint(); //(4)
}
}
(在上面的代码中,this.draw
是代表此Pigeon的PigeonShape对象,CURIOUS
是一个私有(private)静态Color,等于Color.GREEN)
问题在于,在正常执行中,PigeonShape 移动,第 (3) 行和第 (4) 行已完成,但第 (1) 和 (2) 行未完成。在窗口中,它保留了鸽子之前的位置:
(当PigeonShape为绿色时,表示它好奇,当它为蓝色时,表示它正在 sleep )
但是当我一步步调试时,第(1)行和第(2)行正确完成,但我没有移动的踪迹!
我不明白为什么它在逐步调试时有效,但在正常执行时却不起作用...你能帮我吗?谢谢!
最佳答案
it keeps previous positions the Pigeon had :
当您重写 paintComponent(...)
方法时,您需要调用 super.paintComponent(...)
作为第一条语句。这将在进行自定义绘画之前清除背景。
关于JAVA/Swing(Eclipse): Program works step by step but not in normal execution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40325323/