Java Reference
In-Depth Information
public class StackOverflowApp1 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
ListView<Question> listView = new ListView<>();
listView.setItems(getObservableList());
StackPane root = new StackPane();
root.getChildren().add(listView);
Scene scene = new Scene(root, 500, 300);
primaryStage.setTitle("StackOverflow List");
primaryStage.setScene(scene);
primaryStage.show();
}
ObservableList<Question> getObservableList() {
ObservableList<Question> answer = FXCollections.observableArrayList();
long now = System.currentTimeMillis();
long yesterday = now - 1000 * 60 * 60 * 24;
Question q1 = new Question("James", "How can I call a REST service?", now);
Question q2 = new Question("Stephen", "Does JavaFX work on Android?", yesterday);
answer.addAll(q1, q2);
return answer;
}
}
If you have read the previous chapters, this code does not contain anything new. We create a
ListView
, add it to a
StackPane
, create a
Scene
, and render the
Stage
.
The
ListView
is populated with an
ObservableList
containing
Question
s. This
ObservableList
is obtained by
calling the
getObservableList()
method. In the following samples, we modify this method and show how to retrieve
Question
s from the StackExchange API.
■
the
getObservableList
returns an
ObservableList
. the
ListView
automatically observes this
ObservableList
. as a consequence, changes in the
ObservableList
are immediately rendered in the
ListView
control.
in a later sample, we leverage this functionality.
Note
Running this example results in the window shown in Figure
11-3
.
Search WWH ::
Custom Search