2013-12-20 18 views
4

我在JavaFX預加載程序中遇到問題。在開始階段,應用程序將不得不連接到數據庫並閱讀很多內容,因此我認爲在此期間顯示啓動畫面會很好。問題是ProgressBar自動進入100%,我不明白爲什麼。JavaFX預加載程序未更新進度

應用程序類。線程睡眠會真正的代碼後(DB連接等)

public void init() throws InterruptedException 
{ 
    notifyPreloader(new Preloader.ProgressNotification(0.0)); 
    Thread.sleep(5000); 
    notifyPreloader(new Preloader.ProgressNotification(0.1)); 
    Thread.sleep(5000); 
    notifyPreloader(new Preloader.ProgressNotification(0.2)); 
} 

預載

public class PreloaderDemo extends Preloader { 

ProgressBar bar; 
Stage stage; 

private Scene createPreloaderScene() { 
    bar = new ProgressBar(); 
    bar.getProgress(); 
    BorderPane p = new BorderPane(); 
    p.setCenter(bar); 
    return new Scene(p, 300, 150);   
} 

@Override 
public void start(Stage stage) throws Exception { 
    this.stage = stage; 
    stage.setScene(createPreloaderScene());   
    stage.show(); 
} 

@Override 
public void handleStateChangeNotification(StateChangeNotification scn) { 
    if (scn.getType() == StateChangeNotification.Type.BEFORE_START) { 
     stage.hide(); 
    } 
} 

@Override 
public void handleProgressNotification(ProgressNotification pn) { 
    bar.setProgress(pn.getProgress()); 
    System.out.println("Progress " + bar.getProgress()); 
} 

替代出於某種原因,我得到以下輸出:

進度0.0 進度1.0

回答

7

我有同樣的問題,經過兩個小時的搜索和5分鐘的仔細閱讀JavaDoc,我找到了解決方案。:)

通過notifyPreloader()發送的通知方法只能通過Preloader.handleApplicationNotification()方法處理,並且無論您發送哪種類型的通知。

所以改變你這樣的代碼:

public class PreloaderDemo extends Preloader { 

    .... everything like it was and add this ... 

    @Override 
    public void handleApplicationNotification(PreloaderNotification arg0) { 
      if (arg0 instanceof ProgressNotification) { 
      ProgressNotification pn= (ProgressNotification) arg0; 
      bar.setProgress(pn.getProgress()); 
      System.out.println("Progress " + bar.getProgress()); 
      } 
    } 
}