簡體   English   中英

Thread.sleep()不起作用

[英]Thread.sleep() not working

嘗試在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();
        }
    }
}

我希望這足以完成我的代碼,如果我應該上傳完整的代碼,請詢問。

在此先感謝您的時間。

setBounds是否包括重繪/渲染步驟? 如果不是這樣,在keyPressed內部阻塞可能會阻止重繪發生,直到所有睡眠都完成並且keyPressed返回為止。

也許在這行代碼中有一個異常poppetje2.setBounds(poppetje2.getX(), (poppetje2.getY()-5), poppetje1.getIconWidth(), poppetje1.getIconHeight()); 它直接在catch語句上跳轉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM