というわけで、レーシングプログラムを作ろうとしています。この場合、ユーザーが完全に停止するのではなく W キーを離したときに、速度が 0 になるまで車を減速させたいと考えています。
コードは次のとおりです。
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キーを離すと。1 秒間待った後、突然 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