我有工作要做上学。有一个窗口,那里有鸽子,然后单击鼠标,我们放置了鸽子必须吃的食物。为简单起见,我使用秋千来绘制一些用于食物的实心圆形和用于鸽子的实心正方形。鸽子和食物是具有作为JPanels的PigeonShape或FoodShape对象的线程。

当我放置食物时,鸽子会朝着正确的方向运动。问题在于,因为使用挥杆动作,所以每次更改其位置时都必须重新绘制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是等于Color.GREEN的私有静态Color)

问题在于,在正常执行中,PigeonShape会移动,完成第(3)和(4)行,但没有完成(1)和(2)。在窗口中,它保留鸽子先前的位置:java - JAVA/Swing(Eclipse):程序会逐步运行,但无法正常执行-LMLPHP

(当PigeonShape是绿色时,它表示它很好奇,而当它是蓝色时,它处于睡眠状态)

但是,当我逐步调试时,第(1)和(2)行正确完成了,我没有前进的步伐!

我不明白为什么在逐步调试时无法正常运行,但在正常执行中却无法正常工作...您能帮我吗?谢谢 !

最佳答案

它保持了鸽子以前的位置:


覆盖super.paintComponent(...)方法时,需要调用paintComponent(...)作为第一条语句。在执行自定义绘画之前,这将清除背景。

10-04 21:28