如何为JavaFX设置项目TableView - 对象包含另一个对象?

mar*_*kus 5 javafx

我希望尽可能简短,不要忽略有用的信息.我有以下课程:

public class Address{
StringProperty city = new SimpleStringProperty();
StringProperty street = new SimpleStringProperty();

//following the constructor, getters and setters
...
}
Run Code Online (Sandbox Code Playgroud)

我有另一个类Client,一个有一个Address成员

public class Client {

StringProperty name = new SimpleStringProperty();
StringProperty  id = new SimpleStringProperty();
ObjectProperty<Address> address = new SimpleObjectProperty<>();

//following the constructor, getters and setters
...
}
Run Code Online (Sandbox Code Playgroud)

和一个带有控制器的JavaFX接口,该控制器包含一个TableView对象,该对象应该在3列中输出Client类的成员和给定对象的Address类的city成员.我的TableView和TableColumn定义是以下代码

public class SettingsController {
TableColumn<Client, String> clientNameCol;
TableColumn<Client, String> clientEmailCol;
TableColumn<Client, String> clientCityCol;
private TableView<Client> clientSettingsTableView;
...
...
    clientNameCol = new TableColumn<>("Name");
    clientNameCol.setCellValueFactory(new PropertyValueFactory<Client, String>("name"));

    clientEmailCol = new TableColumn<>("email");
    clientEmailCol.setCellValueFactory(new PropertyValueFactory<Client, String>("email"));

    clientCityCol = new TableColumn<>("City");
    clientCityCol.setCellValueFactory(new PropertyValueFactory<Client, String>("city"));

    clientSettingsTableView.setItems(clientData);
    clientSettingsTableView.getColumns().clear();
    clientSettingsTableView.getColumns().addAll(clientNameCol, clientEmailCol, clientCityCol);
Run Code Online (Sandbox Code Playgroud)

当然还有一个ObservableList clientData,它包含一个Client对象数组.一切正常,除了应该为每个客户输出城市的列.我应该如何定义Client对象的城市列(由Address成员包含)?

mar*_*kus 6

@invariant感谢您的帮助,我google了一点点,我最终得到了以下解决方案:

clientCityCol = new TableColumn<>("City");
clientCityCol.setCellValueFactory(new PropertyValueFactory<Client, Address>("address"));
// ======== setting the cell factory for the city column  
clientCityCol.setCellFactory(new Callback<TableColumn<Client, Address>, TableCell<Client, Address>>(){

        @Override
        public TableCell<Client, Address> call(TableColumn<Client, Address> param) {

            TableCell<Client, Address> cityCell = new TableCell<Client, Address>(){

                @Override
                protected void updateItem(Address item, boolean empty) {
                    if (item != null) {
                        Label cityLabel = new Label(item.getCity());
                        setGraphic(cityLabel);
                    }
                }                    
            };               

            return cityCell;                
        }

    });
Run Code Online (Sandbox Code Playgroud)

Address类有一个getter getCity(),它将city成员作为String()返回.