Java Reference
In-Depth Information
The main method is not different from the previous example, apart from the addition of a
System.out
log
message that will print a message when we are done with the setup.
The
getObservableList
method will first create an instance of
ObservableList
, and this instance is returned on
method completion. Initially, this instance will be an empty list. In this method, an instance of
QuestionRetrievalService
is created and the location of the REST endpoint is passed in the constructor. The
QuestionRetrievalService
, which
extends
javafx.concurrent.Service
, is started, and we listen for changes in the
State
of the Service. When the state of
the Service changes to
State.SUCCEEDED
, we add the retrieved questions to the
ObservableList
. Note that on every state
change in the instance of the
QuestionRetrievalService
, we log a message to
System.out
.
We now take a closer look at the
QuestionRetrievalService
to understand how it starts a new
Thread
, and how
it makes sure that the retrieved questions are added to the
ListView
control using the JavaFX
Thread
. The code of the
QuestionRetrievalService
is shown in Listing 11-14.
Listing 11-14.
QuestionRetrievalService
package projavafx;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonValue;
public class QuestionRetrievalService extends Service<ObservableList<Question>> {
private String loc;
public QuestionRetrievalService(String loc) {
this.loc = loc;
}
@Override
protected Task<ObservableList<Question>>createTask() {
return new Task<ObservableList<Question>>() {
@Override
protected ObservableList<Question> call() throws Exception {
URL host = new URL(loc);
JsonReader jr = Json.createReader(new GZIPInputStream(host.openConnection().
getInputStream()));
Search WWH ::
Custom Search