分页内容的异步加载

时间:2013-04-22 21:09:09

标签: asynchronous pagination controls javafx-2

我正在搜索从服务器异步加载数据的分页示例。我不知道如何用javafx的分页控制来解决这个问题。好吧,我有一个例子,其中一个可观察列表在后台加载了10k项。但我只想在实际需要时加载页面的项目。因此,只有当用户切换到下一页时,我才想用任务抓住接下来的20个项目。任务完成后,应该呈现页面..

感谢您的任何建议和帮助!

链接到可观察的示例: https://forums.oracle.com/forums/thread.jspa?messageID=10976705#10976705

1 个答案:

答案 0 :(得分: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);
    }
}