我需要在屏幕上弹起图像。我试图通过将图像向上移动5个单位,然后暂停一秒钟,然后再向上移动5个单位,依此类推。我正在尝试向上移动5次,然后向下移动5次,并间隔一秒钟在每个班次之间。我需要帮助使计时器保持一秒钟,因此它就像每个班次之间的休息一样。我需要编写time()方法。
public void moveIt(KeyEvent evt) throws InterruptedException {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DOWN:
myY += 0;
break;
case KeyEvent.VK_UP:
for (int i = 1; i <= 10; i++) {
if (i <= 5) {
bounceUp();
} else {
bounceDown();
}
time();
}
break;
case KeyEvent.VK_LEFT:
myX -= 5;
break;
case KeyEvent.VK_RIGHT:
myX += 5;
break;
}
repaint();
}
Timer timer = new Timer();
public void bounceUp() throws InterruptedException {
myY -= 10;
}
public void bounceDown() throws InterruptedException {
myY += 10;
}
public void time() {
}
答案 0 :(得分:0)
尝试一下:
try{
Thread.sleep(1000);
}catch(InterruptedException e) {
}
答案 1 :(得分:0)
TimerTask task = new TimerTask()
{
@Override
public void run()
{
time();//executed each second
}
}
timer.schedule(TimerTask task,1000,1000)
应该有帮助
答案 2 :(得分:0)
欢迎您! 尝试在Timer中使用时间表,例如:
Timer timer = new Timer();
timer.schedule(new YourClass(), 0, 1000);
此外,在同一问题上,这也是一个很好的答案: https://stackoverflow.com/a/12908477/10713658