그래서 저는 경주 프로그램을 만들려고합니다. 이 경우, 사용자가 정차하지 않고 W 키를 놓을 때 속도가 0이 될 때까지 차를 감속시키고 싶습니다. 나는 W 키를 놓을 때, 다음레이블 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;
}
그러나 :
여기에 코드입니다. 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
왜 타이머를 다시 시작한 다음 중지합니까? – Qwerky
Thread.sleep (int)에 의해 중단 된 무엇이든지간에 꽤 논리적이고 적절한 타이밍 – mKorbel
나는 그것을 사용하는 방법을 모른다. 나는 단지 그들을 봤다. –