JAVA/Swing(Eclipse): Program works step by step but not in normal execution

标签 java eclipse swing

我有一份工作要为学校做。有一个窗口,里面有鸽子,通过点击鼠标我们放置一些鸽子必须吃的食物。为了简单起见,我使用 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) 行未完成。在窗口中,它保留了鸽子之前的位置:enter image description here

(当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/

相关文章:

java - 如何在 IntelliJ IDEA 调试器中按名称对属性进行排序?

java - 如何在 int 数组中查找元素的索引?

java - WebDriver 打印错误的条件语句

java - 如何垂直对齐 JLabel-JTextField 对

java - 序列化 Java 8 流

java - 如何检查复选框是否已被选中

java - 在 Eclipse 中使用 java 闭包?

javascript - 在 Eclipse 中禁用检查特定的 JavaScript 错误

java - drawString() 没有在我的游戏中绘制字符串

java - 圆形 JPanel Swing