Thread.sleep()不起作用

时间:2015-02-05 13:11:02

标签: java thread-sleep

虽然尝试在java中进行游戏字符跳转,但我尝试使用Thread.sleep()使图像向上移动5个像素,然后等待例如100毫秒,然后再向上移动5个像素等。

相反,当图像需要每步5个像素的5个步长,并且每次等待100毫秒时,它等待500毫秒并向上移动25个像素。

我无法解释这种行为,并且似乎没有在线答案。请注意,我的程序不包含线程。这是我的代码:

ImageIcon poppetje1         = new ImageIcon("img/poppetje1.jpg");
JLabel    poppetje2         = new JLabel(poppetje1);

...

public void jump() {
    try {
        poppetje2.setBounds(poppetje2.getX(), (poppetje2.getY()-5), poppetje1.getIconWidth(), poppetje1.getIconHeight());
        Thread.sleep(100);
    } catch(InterruptedException e) {
        e.printStackTrace();
    }
}

...

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_W) {
        for(int c = 0; c < 10; c++) {
            jump();
            repaint();
        }
    }
}

我希望这足够我的代码,如果我要上传完整的代码,请询问。

提前感谢您的时间。

2 个答案:

答案 0 :(得分:2)

setBounds是否包含重绘/渲染步骤?如果没有,阻塞keyPressed可能会阻止重绘,直到睡眠全部完成并且keyPressed返回。

答案 1 :(得分:0)

也许你在这行代码poppetje2.setBounds(poppetje2.getX(), (poppetje2.getY()-5), poppetje1.getIconWidth(), poppetje1.getIconHeight());中得到一个例外,并且它直接跳转到catch语句。