gpt4 book ai didi

java - 标签设置范围延迟(以秒为单位)

转载 作者:行者123 更新时间:2023-11-30 04:17:16 28 4
gpt4 key购买 nike

所以,我正在尝试制作一个赛车程序。在本例中,我希望汽车减速,直到速度为 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 键时。它等待了一整秒,然后突然向右传送 100 像素并停止。

我还尝试使用 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

最佳答案

这个example使用阻尼 Spring 模型来模拟这种减速。 javax.swing.Timer 用于控制动画的节奏。

image

关于java - 标签设置范围延迟(以秒为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18057920/

28 4 0