有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中暂停并恢复动画(thread.sleep)

我正在尝试暂停并恢复动画。不幸的是,我只能通过使用Thread.sleep();暂停它,而无法在停止的地方恢复它。有人能告诉我如何暂停并恢复带有动画的Thread

这是我当前暂停的方式:

try {
    Thread.sleep(4000);
} catch (InterruptedException ex) {

}

y++; 
Panel.repaint();

共 (3) 个答案

  1. # 1 楼答案

    使用Thread.sleep(4000)只需将整个线程暂停4000毫秒

    我不知道如何从线程内部暂停和取消暂停线程,但我认为如果从另一个线程调用sleep方法,应该是可能的

  2. # 2 楼答案

    您可以使用Java Timer

            TimerTask repeatedTask = new TimerTask() {
                public void run() {
                     Panel.repaint();
                }
            };
            Timer timer = new Timer("Timer");
    
            long period = 4000L;
            timer.scheduleAtFixedRate(repeatedTask, 0, period);
    

    请注意,您可以随时通过调用来取消计时器:Timer.cancel()

  3. # 3 楼答案

    启动线程时,可以添加线程运行的条件。如果更改此条件,可以暂停动画,动画将在停止的位置继续

    boolean pause;
    thr = new Thread(new Runnable(){
    public void run(){
      while(!thr.isInterrupted()&&pause==false){
            try{
                 Thread.sleep(t);
            }catch(Exception e){
                  e.printStackTrace();
            }
            action();   
       }
    }
    });
    thr.start();