许多表列与getter和setter

时间:2016-09-09 06:01:10

标签: arraylist javafx tableview getter-setter tablecolumn

我知道如果我有2列,我必须设置下面的getter和setter

private SimpleIntegerProperty num;
private SimpleStringProperty name;

public GradeCat1st1(){
    this.num = new SimpleIntegerProperty();
    this.name = new SimpleStringProperty();
}

public GradeCat1st1(Integer num, String name){
    this.num = new SimpleIntegerProperty(num);
    this.name = new SimpleStringProperty(name);
}

public Integer getNum(){
    return num.get();
}

public void setNum(Integer num){
    this.num.set(num);
}

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

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

此处调用属性值代码。

tcName.setCellValueFactory(new PropertyValueFactory("name"));
tcNum.setCellValueFactory(new PropertyValueFactory("num"));

但是,如果我有超过10或20列,我是否必须将每列放入getter和setter?

我想制作类似于SimpleStringproperty的arraylist,但不知道。

1 个答案:

答案 0 :(得分:0)

通过使用自定义cellValueFactory,您可以从自定义数据结构中检索数据。

我建议使用ObservableList并使用Bindings类检索数据。以下示例还说明了如何使表格可编辑。

@Override
public void start(Stage primaryStage) {
    TableView<ObservableList<String>> table = new TableView<>(FXCollections.observableArrayList(
            FXCollections.observableArrayList("A", "B", "C"),
            FXCollections.observableArrayList("D")
    ));
    // find size of longest list
    final int columns = table.getItems().stream().mapToInt(ObservableList::size).max().orElse(0);

    table.setEditable(true);

    for (int i = 0; i < columns; i++) {
        TableColumn<ObservableList<String>, String> column = new TableColumn<>("column "+i);
        column.setCellFactory(TextFieldTableCell.forTableColumn());
        final int index = i;

        // use index in list corresponding to column index
        column.setCellValueFactory(cd -> Bindings.valueAt(cd.getValue(), index));

        // write to index on a commit
        // (necessary, since Bindingx.valueAt doesn't return a WritableValue)
        column.setOnEditCommit(evt -> {
            ObservableList<String> item = evt.getRowValue();
            String newValue = evt.getNewValue();
            if (item.size() <= index) {
                // pad with null
                for (int j = item.size(); j < index; j++) {
                    item.add(null);
                }

                item.add(newValue);
            } else {
                item.set(index, newValue);
            }
        });
        table.getColumns().add(column);
    }

    // button for printing the contents to console to show the lists are updated
    Button btn = new Button("Print");
    btn.setOnAction((ActionEvent event) -> {
        System.out.println(table.getItems());
    });

    Scene scene = new Scene(new VBox(table, btn));

    primaryStage.setScene(scene);
    primaryStage.show();
}