Java Reference
In-Depth Information
is the
java.util.ArrayList
class. When building applications with domain ob-
jects that contain an
ArrayList
, developers can easily manipulate objects inside the
collection. But, in the past (back in the day), when using Java Swing components com-
bined with collections was a challenge, especially updating the GUI to reflect changes
in the domain object. How do you resolve this issue? Well, JavaFX's
Observ-
ableList
to the rescue!
Speaking of rescue, this recipe demonstrates a GUI application to allow users to
choose their favorite heroes. This is quite similar to application screens that manage
user roles by adding or removing items from list box components. In JavaFX, use a
ListView
control to hold string objects. Before creating an instance of a
ListView
,
the
ObservableList
containing the candidates is created. In the example, you'll
notice the use of a factory class called
FXCollections
, in which you can pass in
common collection types to be wrapped and returned to the caller as an
Observ-
ableList
. This recipe passes in an array of strings instead of an
ArrayList
, so
hopefully you get the idea about how to use the
FXCollections
class. Be sure to
use it wisely: “With great power, there must also come great responsibility.” This code
line calls the
FXCollections
class to return an observable list (
Observ-
ableList
):
ObservableList<String> candidates
= FXCollections.observableArrayList(...);
After creating an
ObservableList
, a
ListView
class is instantiated using a
constructor that receives the observable list. Shown here is code to create and populate
a
ListView
object:
ListView<String> candidatesListView = new
ListView<String>(candidates);
In the last item of business, the code will manipulate the
ObservableList
s as if
they were
java.util.ArrayList
s. Once manipulated, the
ListView
will be
notified and automatically updated to reflect the changes of the
ObservableList
.
The following code snippet implements the event handler and action event when the
user presses the send right button:
// select heroes
Button sendRightButton = new Button(">");
sendRightButton.setOnAction((e) -> {