Defining TableView Columns

To define the columns in our TableView we use the methods shown in this snippet from Listing 6-6: TableColumn firstNameColumn = new TableColumn("First Name"); firstNameColumn.setCellValueFactory(new PropertyValueFactory("firstName")); firstNameColumn.setPrefWidth(180);

The String parameter we provide to the constructor specifies the text that should appear in the column header, and the setPrefWidth() method specifies the column’s preferred width in pixels.

The argument passed into the setCellValueFactory() method specifies a property that will be used to populate this column. In this case, the property is the firstNameProperty defined in the Person model class of our StarterApp program, shown in Listing 6-7.

Listing 6-7. The Source Code for Person.java

public final class Person {
  private StringProperty firstName;
  public void setFirstName(String value) { firstNameProperty().set(value); }
  public String getFirstName() { return firstNameProperty().get(); }
  public StringProperty firstNameProperty() {
    if (firstName == null) firstName = new SimpleStringProperty(this, "firstName");
    return firstName;
  }

  private StringProperty lastName;
  public void setLastName(String value) { lastNameProperty().set(value); }
  public String getLastName() { return lastNameProperty().get(); }
  public StringProperty lastNameProperty() {
    if (lastName == null) lastName = new SimpleStringProperty(this, "lastName");
    return lastName;
  }

  private StringProperty phone;
  public void setPhone(String value) { phoneProperty().set(value); }
  public String getPhone() { return phoneProperty().get(); }
  public StringProperty phoneProperty() {
    if (phone == null) phone = new SimpleStringProperty(this, "phone");
    return phone;
  }

  public Person(String firstName, String lastName, String phone) {
    setFirstName(firstName);
    setLastName(lastName);
    setPhone(phone);
  }

  public String toString() {
    return "Person: " + firstName.getValue() + " " + lastName.getValue();
  }
}

Detecting When a Row Is Selected

To detect when the user selects a row in the TableView, the StarterApp program adds a ChangeListener to the selectedItem property of the table view’s selection model. The code for accomplishing this is shown in this snippet from Listing 6-6:

table.getSelectionModel().selectedItemProperty()
            .addListener((ObservableValue observable, Object oldValue, Object newValue) -> {
                Person selectedPerson = (Person) newValue;
                System.out.println(selectedPerson + " chosen in TableView");
            });

When the user selects a row, the lambda expression is invoked, which prints data from the underlying Person instance represented by that row. This is the behavior you observed in Step 7 of the previous exercise.

Now that we’ve explored some of the capabilities of the TableView, let’s move on to the next tab, Accordion/TitledPane.