2013-08-05 30 views
1

所以,我正在尝试制作一个赛车程序。在这种情况下,当用户释放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

+0

为什么你重新启动,然后停止你的计时器? – Qwerky

+0

从Thread.sleep(int) – mKorbel

+0

停止的任何时候都是非常合乎逻辑和合适的时机。我真的不知道如何使用它。我只是搜索了他们。 –

回答

2

这个example使用阻尼弹簧模型来模仿这种减速。 A javax.swing.Timer用于调节动画。

image

+0

唯一帮助我了解的例子是定时器的结构和定时器的actionPerformed内部的东西。这非常有帮助,现在我的车缓慢减速。谢谢! –

+0

@JuvarAbrera:很高兴帮助;即使你没有使用引用的模型,它可能会引导你封装自己的模型。 – trashgod

0

而不是做carPositionX+=carAcceleration尝试carPositionY+=carAccleration。这应该使汽车在窗口坐标系的y轴上移动。

+0

失败。你没有得到我的问题。不过谢谢。 –