Lesson 10

MVC Table

How to use a table component in JavaFX?

Task 0

Create POJO object for class named Person:


public class Person {

    private String firstName = null;
    private String lastName = null;

    public Person() {
    }

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Person{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}
Task 1

Create a fxml view with TableView. Set value of fx:id as tableView. Remove any columns from view.

Task 2

Create controller class for the view. Create a field TableView<Person> named as tableView. Implement javafx.fxml.Initializable interface. Create all columns using structure:


TableColumn<Person, String> firstNameColumn = new TableColumn<>("Last Name");
firstNameColumn.setCellValueFactory(new PropertyValueFactory<>("firstName"));
tableView.getColumns().add(firstNameColumn);
    
Task 3

Create a method loadData() and call it inside initialize method. Add some data i.e.:


tableView.getItems().add(new Person("John", "Doe"));
tableView.getItems().add(new Person("Jane", "Deer"));
Task 4

After selecting a record, a person should greet him/herself like: "Hi, I am John Doe!"


TableView.TableViewSelectionModel<Person> selectionModel = tableView.getSelectionModel();
ObservableList<Person> selectedItems = selectionModel.getSelectedItems();
selectedItems.addListener((ListChangeListener:<? super Person>) change -> {
    System.out.println(change.getList());
});
                
Task 5

Create a form (inside the same window), that will allow an user to crate a new record to a table. Also add 2 fields more (modify Person class, table and form).