Java Reference
In-Depth Information
How It Works
Just for fun we created a simple GUI to display employees and their bosses. You notice
in
Figure 14-13
on the left is a list of people (the bosses). When users select a boss,
their employees will be shown to in the
TableView
area to the right. You'll also no-
tice the tooltip when you hover over the selected boss.
Before considering the
TableView
control, it's important that you understand the
ListView
that is responsible for updating the
TableView
. In model-view fashion,
an
ObservableList
is created that contains all the bosses for the
ListView
con-
trol's constructor. This code calls the bosses
leaders
. The following code creates a
ListView
control:
// List of leaders
ObservableList<Person> leaders = getPeople();
final ListView<Person> leaderListView = new
ListView<Person>(leaders);
Next, create a cell factory to properly display the person's name in the
ListView
control. Because each item is a
Person
object, the
ListView
does not know how to
render each row in the
ListView
control. You simply create a
javafx.util.Callback
generic type object by specifying the
ListView<Per-
son>
and a
ListCell<Person>
data types. If you're using a trusty IDE such as
NetBeans, it will pregenerate things such as the implementing method
call()
. Next
is the variable cell of type
ListCell<Person>
(within the
call()
method), in
which you create a lambda expression. The lambda expression contains an implement-
ation for an
updateItem()
method. To implement the
updateItem()
method,
obtain the person information and update the
Label
control (
leadLbl
). Lastly, you
set the tooltip to the associated text.
You then create a
TableView
control to display the employee base on the selec-
ted boss from the
ListView
. When creating a
TableView
, first create the column
headers. Use the following code to create a table column:
TableColumn<String> firstNameCol = new
TableColumn<String>("First Name");
firstNameCol.setProperty("firstName");