2015-01-02 57 views
2

我試圖通過使用for循環獲取圖像的ArrayList並將它們放入ImageView來創建幻燈片。但是,爲了「暫停」程序以便每個圖像都可見,我正在嘗試使用Thread.sleep。這不幸的是沒有達到預期的效果。爲了彌補這一點,我無休止的谷歌搜索導致我懷疑我應該使用Timeline類,但我不知道如何實現它。任何幫助將非常感激。我的,因爲它代表不正常的代碼如下所示:使用JavaFX從圖像ArrayList幻燈片

for (int i = 0; i < imageArrayList.size(); i++) { 
    try { 
     Thread.sleep(1000); 
    } catch (Exception e) { 
     System.out.println("Error: " + e.toString()); 
    } 
    slideshowImageView.setImage(imageArrayList.get(i)); 
} 
+0

做一些研究,在JafaFx併發的,你需要設置某種定時器將GUI線程 – MadProgrammer

+0

我的上下文中觸發回調方法下面貼的回答,請讓我知道,如果它有助於/於事無補 – Victor2748

回答

1

使用Timer更新圖像每一定毫秒

public int count = 0; 

// then in your method 

long delay = 2000; //update once per 2 seconds. 
new Timer().schedule(new TimerTask() { 

    @Override 
    public void run() { 
     slideshowImageView.setImage(imageArrayList.get(count++)); 
     if (count >= imageArrayList.size() { 
      count = 0; 
     } 
    } 
}, 0, delay); 

此外,slideshowImageViewimageArrayList一次必須是域,或final變量,可以在`TimerTask`中訪問。

+0

不,感謝您的快速反應,但你的代碼給這個錯誤'code'異常在線程「定時器2」異常線程「定時器-10」中的異常線程「定時器-6」的異常在線程「定時器-0」中的異常線程「定時器-8」的異常在線程「定時器-5」 java.lang.IllegalStateException:不上FX應用程序線程; currentThread = Timer-8'code' – agelston

+0

@agelston好吧,什麼是完整的堆棧跟蹤?你知道問題嚴重嗎?引擎收錄我的完整的堆棧跟蹤,我會改正我的答案(也,你能告訴我,什麼是行號「新的Timer()。日程(新的TimerTask(){」在你的java文件行? – Victor2748

+0

謝謝男人,你必須在這裏原諒我的無知,我可TAD超出我的深度....通過完整的堆棧跟蹤你的意思是這樣http://pastebin.com/bqpFDpE8新的計時器語句上線244 – agelston

2

想通了後好長時間,而谷歌搜索

int count; //declared as global variable   



//then the working logic in my eventhandler 
    Task task = new Task<Void>() { 
        @Override 
      public Void call() throws Exception { 
         for (int i = 0; i < imageArrayList.size(); i++) { 
          Platform.runLater(new Runnable() { 
           @Override 
      public void run() { 
            slideshowImageView.setImage(imageArrayList.get(slideshowCount)); 
            slideshowCount++; 
            if (slideshowCount >= imageArrayList.size()) { 
             slideshowCount = 0; 
            } 
           } 
          }); 

         Thread.sleep(1000); 

        } 
        return null; 
       } 
      }; 
      Thread th = new Thread(task); 
      th.setDaemon(true); 
      th.start(); 

     });