2

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

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

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

4

1 回答 1

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);
    }
}
于 2013-04-24T12:44:36.367 回答