Pavel Pavel - 5 months ago 17
Java Question

TableView binding and Object HAS-A relation

I have the following classes

Class Car{
private StringProperty type;

//+setters and getters

Class Person{
private Car car;

private StringProperty name;

//+setters and getters

And I have tableView
. In this tableView I have two columns - Person Name and Car Type.

This is how I build column for Person Name

TableColumn<Person,String> column=new TableColumn("Person Name");

You can see, there can be two changes with Car in class Person. First of all a person can get another car, and secondly car can change its type.

How can I build column Car Type and bind to "these two changes"

Answer Source

The select* methods of the Bindings class are made for this:

    data -> Bindings.selectString(data.getValue(), "car", "type"));

Note that your getters and setters should follow JavaFX conventions, like all JavaFX classes do:

class Car {
    private final StringProperty type = new SimpleStringProperty();

    public StringProperty typeProperty() { return type; }
    public String getType() { return type.get(); }
    public void setType(String newType) { type.set(newType); }

class Person {
    private final ObjectProperty<Car> car = new SimpleObjectProperty<>();

    private final StringProperty name = new SimpleStringProperty();

    public ObjectProperty<Car> carProperty() { return car; }
    public Car getCar() { return car.get(); }
    public void setCar(Car newCar) { car.set(newCar); }

    public StringProperty nameProperty() { return name; }
    public String getName() { return name.get(); }
    public void setName(String newName) { name.set(newName); }