Java Reference
In-Depth Information
public List<Question> getItem() {
return item;
}
public void setItem(List<Question> item) {
this.item = item;
}
}
The QuestionResponse class itself has two annotations:
@XmlAccessorType(XmlAccessType.FIELD)
was already discussed before and
@XmlRootElement(name="items")
indicates that this class corresponds to a root object in the XML structure, with the name “items.” This indeed
corresponds to the syntax of the XML response we created in Listing 11-6.
The previous examples show how existing technologies available in the Java 2 Platform, Standard Edition, can be
used to obtain data from web services and inject these data in JavaFX controls. We now modify the example code to
take advantage of some specific features of the JavaFX Platform.
Asynchronous Processing
A major problem with the examples so far is that they block the UI during the process of data retrieval and parsing. In
many real-world situations, this is unacceptable. Calls to external web services might take longer than expected due
to network or server issues. Even when the external calls are fast, a temporarily unresponsive UI decreases the overall
quality of the application.
Fortunately, the JavaFX Platform allows for concurrency and asynchronous tasks. The concepts of Task,
Worker, and Service have already been discussed in Chapter 7. In this section, we show how to leverage the
javafx.concurrent package when accessing web services. We also leverage the fact that the ListView watches the
ObservableList that contains its items.
The basic idea is that, when creating the ListView , we immediately return an empty ObservableList , while
retrieving the data in a background Thread . Once we retrieve and parse the data, we add it to the ObservableList and
the result will immediately be visible in the ListView .
The main class for this example is shown in Listing 11-13. We started with the code in Listing 11-7, where
we obtained the questions in JSON format using a REST request to the StackExchange API. With some minor
modifications, we could use the XML response as well, though.
Listing 11-13. Use a Background Thread for Retrieving Question ListView .
package projavafx;
import java.io.IOException;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
 
Search WWH ::




Custom Search