所以,我正在尝试制作一个赛车程序。在这种情况下,当用户释放W键而不是完全停止时,我希望汽车减速直到速度为0。Label Setbounds以秒为单位的延迟
下面的代码:
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
为什么你重新启动,然后停止你的计时器? – Qwerky
从Thread.sleep(int) – mKorbel
停止的任何时候都是非常合乎逻辑和合适的时机。我真的不知道如何使用它。我只是搜索了他们。 –