标签设置延迟(以秒为单位)

时间:2013-08-05 12:15:51

标签: java swing delay event-dispatch-thread thread-sleep

所以,我正在努力制作赛车计划。在这种情况下,我希望汽车减速直到速度为0,因为用户释放了W键而不是完全停止。

以下是代码:

JLabel carImage = new JLabel(new ImageIcon("carimage.jpg"));
int carAcceleration = 100;
int carPositionX = 0, carPositionY = 100;
// assume it is already add in the container

public void keyReleased(KeyEvent key) {
    handleKeyReleased(key);
}

int slowdown = 0;
Timer timer = new Timer(1000,this); // 1000ms for test
public void handleKeyReleased(KeyEvent key) {
    if(key.getKeyCode() == KeyEvent.VK_W) {
        slowdown=1;
        timer.start();
    }
}

public void actionPerformed(ActionEvent action) {
    if(slowdown == 1) {
        while(carAcceleration> 0) {
            carAcceleration--;
            carPositionX += carAcceleration;
            carImage.setBounds(carPositionX, carPositionY, 177,95);
            timer.restart();
        }
    }
    timer.stop();
    slowdown = 0;
}

但是,当我释放W键时。它等了一整秒,突然向右传送100px并停止。

我也尝试过使用Thread.sleep(1000);但同样的事情发生了。

JLabel carImage = new JLabel(new ImageIcon("carimage.jpg"));
int carAcceleration = 100;
int carPositionX = 0, carPositionY = 100;
// assume it is already add in the container

public void keyReleased(KeyEvent key) {
    handleKeyReleased(key);
}

public void handleKeyReleased(KeyEvent key) {
    if(key.getKeyCode() == KeyEvent.VK_W) {
        while(carAcceleration> 0) {
            carAcceleration--;
            carPositionX += carAcceleration;
            carImage.setBounds(carPositionX, carPositionY, 177,95);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                //
            }
        }
    }
}

我希望它像这样执行。

carAcceleration | carPositionX  | Output    
----------------------------------------------------------------------
100             | 100           | carImage.setBounds(100,100,177,95);
                |               | PAUSES FOR SECONDS 
99              | 199           | carImage.setBounds(199,100,177,95);
                |               | PAUSES FOR SECONDS
98              | 297           | carImage.setBounds(297,100,177,95);
                |               | PAUSES FOR SECONDS
... and so on

提前致谢。 :d

2 个答案:

答案 0 :(得分:2)

example使用阻尼弹簧模型来模拟这种减速。 javax.swing.Timer用于调整动画的速度。

image

答案 1 :(得分:0)

而不是carPositionX+=carAcceleration尝试carPositionY+=carAccleration。这应该使汽车在窗户坐标系的y轴上移动。