动态添加到TableView的绑定

时间:2016-06-04 13:56:03

标签: java javafx

我想创建一个简单的应用程序,根据文件中的数据生成图表。然后,我想动态添加列和绑定到它们。

模型类:

public class ChartData {
private ObservableList<String> series;
private ObservableList<Data> data;

public ChartData(){
    series = FXCollections.observableArrayList();
    data = FXCollections.observableArrayList();
}

//getters, setters ommited
}

public class Data {

private final StringProperty name = new SimpleStringProperty(this, "name");
private final ObservableList<Property<Number>> values = FXCollections.observableArrayList();


public ObservableList<Property<Number>> getValues() {
    return values;
}

public String getName() {
    return name.get();
}

public final StringProperty nameProperty() {
    return name;
}

public void setName(String name) {
    this.name.set(name);
}

public void addValue(Double val) {
    values.add(new SimpleDoubleProperty(val));
}

public Object getFirstValue() {
    return values.get(0).getValue();
}

public Object getValue(int count) {
    return values.get(count).getValue();
}

public Property<Number> getFirstProperty(){
    return this.values.get(0);
}
public Property<Number> getSecondProperty(){
    return this.values.get(1);
}
public Property<Number> getThirdProperty(){
    return this.values.get(2);
}

public Property<Number> getProperty(int count){
    return this.values.get(count);
}

}

绑定方法:

    private <S, T> TableColumn<S,T> createCol(String title,
                                          Function<S,ObservableValue<T>> propertySelector,
                                          StringConverter<T> converter,
                                          boolean editable) {

    TableColumn<S,T> col = new TableColumn<>(title);
    col.setEditable(editable);
    col.setCellFactory(TextFieldTableCell.forTableColumn(converter));
    col.setCellValueFactory(cellData -> propertySelector.apply(cellData.getValue()));
    return col ;
}

硬编码绑定:

    private void initializeTableViewCellFactoryListeners(ChartData chartData) {
    chartDataTableView.getColumns().clear();
    chartDataTableView.getItems().clear();

    // test end.
    DefaultStringConverter def = new DefaultStringConverter();
    NumberStringConverter num = new NumberStringConverter();

    // build columns dynamically!?
    chartDataTableView.getColumns().add(createCol("Name", Data::nameProperty, def, false));

    chartDataTableView.getColumns().add(createCol("Val1", Data::getFirstProperty, num, true));
    //chartDataTableView.getColumns().add(createCol("Val2", Data::getSecondProperty, num, true));
    //chartDataTableView.getColumns().add(createCol("Val3", Data::getThirdProperty, num, true));
}

如何传递Data.getProperty(n)方法而不是Data :: getXXXProperty?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我不确定我完全明白你在问什么:你在寻找

chartDataTableView.getColumns().add(createCol("Val1", 
    data -> data.getProperty(n), 
    num, true));