所以,我正在嘗試製作一個賽車程序。在這種情況下,當用戶釋放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
停止的任何時候都是非常合乎邏輯和合適的時機。我真的不知道如何使用它。我只是搜索了他們。 –