ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaFX:使用REST服务并在前端显示数据

2019-08-29 22:29:27  阅读:265  来源: 互联网

标签:java spring javafx javafx-8 javafx-2


我正在开发一个JavaFX(在带有SceneBuilder的JDK8上)项目,该项目应该与基于Spring-MVC的服务器连接,我想从服务器访问一些对象并显示它.我已经编写了Spring服务器来根据请求回放所需的对象,但是我对UI编程和JavaFX的不熟悉使它变得有点困难.

在FXML文件中,我已经添加了一个网格窗格,我想在那里显示对象.我很感激你们的任何帮助,让我们开始.我只有基本代码,但我在下面粘贴它:

Canvas.fxml:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>

<GridPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8">
  <columnConstraints>
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
    <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  </columnConstraints>
  <rowConstraints>
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
    <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  </rowConstraints>
</GridPane>

CanvasModel类:

public class Canvas {

    private int canvasid;

    private final StringProperty canvasName;

    private final StringProperty canvasTitle;

    private final StringProperty canvasImage;

    private byte[] canvasImageInBytes;


    public Canvas(String canvasName, String canvasTitle, String canvasImage){
        this.canvasName = new SimpleStringProperty(canvasName);
        this.canvasTitle = new SimpleStringProperty(canvasTitle);
        this.canvasImage = new SimpleStringProperty(canvasImage);
    }
//Getters and setters ommitted
}

主要课程:

public class Main extends Application {

    private Stage primaryStage;

    @Override
    public void start(Stage primaryStage) throws Exception{
       Parent root = FXMLLoader.load(getClass().getResource("../View/mainui.fxml"));

primaryStage.setTitle("CheckAPP");
       primaryStage.setScene(new Scene(root, 300, 600));
        primaryStage.setFullScreen(false);
        primaryStage.setMaximized(false);

        primaryStage.show();
    }
    public static void main(String[] args) {
        launch(args);
    }

    public Stage getPrimaryStage() {
        return this.primaryStage;
    }

}

现在向下面发出请求:

http://localhost:8080/canvaslist

它将返回我想在GridPane中显示的java.util.List.图像采用String格式.我明白这不是一个常规问题,因为这不起作用,但我试图绕过我的头脑进行UI编程,我不知道还有什么要转向.非常感谢你的帮助.

解决方法:

只需加上我的几美分来帮助你.

>使用后台线程从服务中获取数据,因为可能需要一段时间才能获得响应.在JavaFX应用程序线程上执行它可能会导致不良用户体验.在这种情况下,Task将帮助您.
>一旦有了响应,就可以从中构造一个必要的对象/对象集合,您将使用它来更新场景图上的元素.
>由于JavaFX Application Thread是您可以访问实时场景图元素的唯一线程,因此您无法在后台线程中直接使用它们(使用它们将导致IllegalStateException).您可以使用Platform.runLater更新JavaFX场景图上的数据,或者调用保证在FX应用程序线程上更新状态的任务方法,如updateProgress(...),updateMessage(...),getValue(...)等.
>使用在步骤2中构建的对象/对象集合来创建(或更新)FX场景图元素.
>如果您有一个接受ObservableList作为其内容的控件(如TableView或ListView),您可以绑定内容和Task的属性之一,在执行期间/之后自动更新它们,具体取决于它们的用法.
>但是在你的情况下,由于你有GridPane,所以我们可能不得不更进一步,编写逻辑来创建控件并将它们添加到GridPane.

我创建了一个使用服务的示例,解析JSON数据并从中创建一个GridPane. JSON列出了StackOverflow上很少有人的名字,他们的名字,他们的喜欢(根据我)和SO上的个人资料.

它使用后台任务从服务加载JSON数据,使用任务的setOnSucceeded(...)处理程序将其传递给创建GridPane的createGridPane(onservableList).

GridPane的其中一列包含相应人员的个人资料图片.由于这些图像可能需要一段时间才能下载,因此我会生成多个线程来为每个用户加载图像.

你可以找到source code here.

它使用GSON作为库将JSON转换为POJO类.

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class ConsumeJSON extends Application {

    private ObservableList<PeopleOnSO> listOfPeople;
    private static final String JSON_URL = "https://api.myjson.com/bins/3jwmh";
    private static final String IMAGE_URL = "http://www.fontspring.com/presentation_20150512/images/ajax_loader_blue_512.gif";
    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private Image loadImage;

    @Override
    public void start(Stage stage) throws Exception {

        loadImage = new Image(IMAGE_URL);
        VBox root = new VBox();
        root.setAlignment(Pos.TOP_CENTER);
        root.setPadding(new Insets(20));
        root.setSpacing(20);

        Button button = new Button("Fill GridPane");

        root.getChildren().addAll(button);


        button.setOnAction(e -> {
            // Display loading image
            ImageView loading = new ImageView(loadImage);
            loading.setFitWidth(60);
            loading.setFitHeight(60);
            root.getChildren().add(loading);
            executorService.submit(fetchList);
        });


        fetchList.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                listOfPeople = FXCollections.observableArrayList(fetchList.getValue());
                GridPane gridPane = createGridPane(listOfPeople);
                //Remove Loading Image and add GridPane
                root.getChildren().remove(1);
                VBox.setVgrow(gridPane, Priority.ALWAYS);
                root.getChildren().add(gridPane);
                stage.sizeToScene();
            }
        });

        ScrollPane scrollPane = new ScrollPane(root);
        Scene scene = new Scene(scrollPane, 600, 500);
        stage.setScene(scene);
        stage.setTitle("Load Data from JSON");
        stage.show();

        stage.setOnCloseRequest(e -> {
            executorService.shutdown();
        });
    }

    public GridPane createGridPane(ObservableList<PeopleOnSO> listOfPeople){
        GridPane gridPane = new GridPane();
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setGridLinesVisible(true);
        gridPane.setPadding(new Insets(20));
        gridPane.setMinHeight(500);
        gridPane.setMaxWidth(500);

        //Create headings
        Label nameHeading = new Label("Name");
        nameHeading.setStyle("-fx-font-weight: bold");
        Label likeHeading = new Label("Likes");
        likeHeading.setStyle("-fx-font-weight: bold");
        Label imageHeading = new Label("Image");
        imageHeading.setStyle("-fx-font-weight: bold");

        gridPane.add(nameHeading, 0, 0);
        gridPane.add(likeHeading, 1, 0);
        gridPane.add(imageHeading, 2, 0);

        // Aligning at center
        alignElements(nameHeading, likeHeading, imageHeading);

        // Setting Constraints
        for (int i = 0; i < 3; i++) {
            ColumnConstraints column = new ColumnConstraints(150);
            // column.setPercentWidth(80);
            gridPane.getColumnConstraints().add(column);
        }

        for (int i = 0; i < listOfPeople.size(); i++) {

            PeopleOnSO people = listOfPeople.get(i);
            Label nameLabel = new Label(people.getName());
            Label likeLabel = new Label(people.getLike());
            ImageView imageView = new ImageView(loadImage);
            imageView.setFitHeight(60);
            imageView.setFitWidth(60);

            //Thread for loading images later
            FetchImage fetchImage = new FetchImage(people.getImageUrl());
            fetchImage.setOnSucceeded(worker -> {
                imageView.setImage((Image) fetchImage.getValue());
            });

            executorService.submit(fetchImage);

            // Adding to GridPane and necessary configuration
            gridPane.add(nameLabel, 0, i + 1);
            gridPane.add(likeLabel, 1, i + 1);
            gridPane.add(imageView, 2, i + 1);

            //Aligning at center
            alignElements(nameLabel, likeLabel, imageView);

            gridPane.getRowConstraints().add(new RowConstraints(80));
        }
        return gridPane;
    }

    /**
     * Align elements at the center
     * @param nodes
     */
    private void alignElements(Node ... nodes ) {
        for(Node node : nodes) {
            GridPane.setHalignment(node, HPos.CENTER);
            GridPane.setValignment(node, VPos.CENTER);
        }
    }

    /**
     * Task to fetch details from JSONURL
     * @param <V>
     */
    private Task<List<PeopleOnSO>> fetchList = new Task() {
        @Override
        protected List<PeopleOnSO> call() throws Exception {
            List<PeopleOnSO> list = null;
            try {
                Gson gson = new Gson();
                list = new Gson().fromJson(readUrl(JSON_URL), new TypeToken<List<PeopleOnSO>>() {
                }.getType());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }
    };

    /**
     * Task to fetch images for individual ImageViews
     * @param <V>
     */
    private class FetchImage<V> extends Task<Image> {

        private String imageUrl;

        public FetchImage(String imageUrl) {
            this.imageUrl = imageUrl;
        }

        @Override
        protected Image call() throws Exception {
            Image image = new Image(imageUrl);
            return image;
        }

    }

    /**
     * Read the URL and return the json data
     * @param urlString
     * @return
     * @throws Exception
     */
    private static String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

            return buffer.toString();
        } finally {
            if (reader != null)
                reader.close();
        }
    }

    private class PeopleOnSO {

        private final String name;
        private final String like;
        private final String imageUrl;

        public PeopleOnSO(String name, String like, String imageUrl){
            this.name = new String(name);
            this.like = new String(like);
            this.imageUrl = new String(imageUrl);
        }

        public String getName() {
            return name;
        }

        public String getLike() {
            return like;
        }

        public String getImageUrl() {
            return imageUrl;
        }
    }

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

标签:java,spring,javafx,javafx-8,javafx-2
来源: https://codeday.me/bug/20190829/1763887.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有