2013-04-22 151 views
2

我正在搜索從服務器加載異步數據的分頁示例。我不知道如何通過javafx的分頁控制來解決這個問題。那麼我有一個例子,其中一個可觀察列表在背景中加載了10k個項目。但是我只想在實際需要時加載頁面的項目。所以只有當用戶切換到下一頁時,我想要抓住接下來的20項任務。當任務完成後,頁面應呈現..分頁內容的異步加載

感謝您的任何建議和幫助!

鏈接到可觀察到的例子: https://forums.oracle.com/forums/thread.jspa?messageID=10976705#10976705

回答

2

所有你需要的是一旦用戶在頁面上點擊啓動一個後臺線程與你的任務。請參閱下一個使用網站下載以執行長時間任務的示例:

public class Pages extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     final Pagination root = new Pagination(urls.length, 0); 

     root.setPageFactory(new Callback<Integer, Node>() { 
      // This method will be called every time user clicks on page button 
      public Node call(final Integer pageIndex) { 
       final Label content = new Label("Please, wait"); 
       content.setWrapText(true); 
       StackPane box = new StackPane(); 
       box.getChildren().add(content); 

       // here we starts long operation in another thread 
       new Thread() { 
        String result; 
        public void run() { 

         try { 
          URL url = new URL(urls[pageIndex]); 
          URLConnection urlConnection = url.openConnection(); 
          urlConnection.setConnectTimeout(1000); 
          urlConnection.setReadTimeout(1000); 
          BufferedReader breader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 

          StringBuilder stringBuilder = new StringBuilder(); 

          String line; 
          while ((line = breader.readLine()) != null) { 
           stringBuilder.append(line); 
          } 

          result = stringBuilder.toString(); 
         } catch (Exception ex) { 
          result = "Download failed"; 
         } 

         // once operation is finished we update UI with results 
         Platform.runLater(new Runnable() { 

          @Override 
          public void run() { 
           content.setText(result); 
          } 
         }); 
        } 
       }.start(); 

       return box; 
      } 
     }); 

     Scene scene = new Scene(root, 300, 250); 

     primaryStage.setTitle("Pages!"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    private final static String[] urls = {"http://oracle.com", "http://stackoverflow.com", "http://stackexchange~.com", "http://google.com", "http://javafx.com"}; 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
+0

我試過了,它按預期工作。感謝謝爾蓋!乾杯,噸 – tonimaroni 2013-04-24 14:12:36