java - JavaFX : Consuming REST service and displaying the data in front-end -
i working on javafx(on jdk8 scenebuilder) project should connect spring-mvc based server , access objects server , display it. have programmed spring server give desired object upon request, unfamiliarity in ui programming , javafx making bit difficult.
in fxml file, have added grid-pane , display objects there. appreciate guys started up. have basic code, pasting below :
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 class :
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 , setters ommitted }
main class :
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; } }
now making request below :
http://localhost:8080/canvaslist
it return java.util.list want display in gridpane. images in string format. understand not regular question not working , all, trying wrap around head ui programming, , didn't knew else turn to. lot help.
just adding few cents you.
- use
background thread
fetch data service, may take time response back. executing on javafx application thread might result in undesirable user experience. in casetask
you. - once have response, construct necessary
object / collection of object
using update elements on scene graph. - since
javafx application thread
thread on can accesslive scene graph
elements, cannot directly use them in background thread ( using them result inillegalstateexception
). can update data on javafx scene graph either usingplatform.runlater
or calling methods oftask
guaranteed update state on fx application thread,updateprogress(...)
,updatemessage(...)
,getvalue(...)
etc. - use
object / collection of object
constructed instep-2
create (or update) fx scene graph elements. - in case have control (like tableview or listview) accepts
observablelist
contents, can bind contents , 1 oftask
's property, update them automatically during/ after execution depending on usage. - but in case, since have
gridpane
, might have take step further , write logic create controls , add themgridpane
.
example
i have created example consumes service, parses json data , creates gridpane
out of it. json has list of few people on stackoverflow
names, likes (according me) , profile pic on so.
it uses background task load json data service, uses setonsucceeded(...)
handler of task pass creategridpane(onservablelist)
creates gridpane
.
one of columns of gridpane
contains profile picture of respective person. since these images can take time download, spawn multiple threads
load image
each user.
you can find source code here.
it uses gson
library convert json
pojo
class.
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 , 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 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 @ center alignelements(nameheading, likeheading, imageheading); // setting constraints (int = 0; < 3; i++) { columnconstraints column = new columnconstraints(150); // column.setpercentwidth(80); gridpane.getcolumnconstraints().add(column); } (int = 0; < 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 loading images later fetchimage fetchimage = new fetchimage(people.getimageurl()); fetchimage.setonsucceeded(worker -> { imageview.setimage((image) fetchimage.getvalue()); }); executorservice.submit(fetchimage); // adding gridpane , necessary configuration gridpane.add(namelabel, 0, + 1); gridpane.add(likelabel, 1, + 1); gridpane.add(imageview, 2, + 1); //aligning @ center alignelements(namelabel, likelabel, imageview); gridpane.getrowconstraints().add(new rowconstraints(80)); } return gridpane; } /** * align elements @ center * @param nodes */ private void alignelements(node ... nodes ) { for(node node : nodes) { gridpane.sethalignment(node, hpos.center); gridpane.setvalignment(node, vpos.center); } } /** * task fetch details 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 fetch images 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 url , return 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(); } { 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); } }
Comments
Post a Comment