简体   繁体   中英

JavaFX TableView seperate bean adapter for each row. How?

Having problems to bind bean adapter objects to TableView, which creates combobox with that adapter property.

lanSpecie.setCellFactory(new Callback<TableColumn<HAUL,Specie>, TableCell<HAUL,Specie>>() {
    @Override
    public TableCell<HAUL, Specie> call(TableColumn<HAUL, Specie> param) {
        TableCell<HAUL, Specie> cell = new TableCell<>();
        ComboBox<Specie> comboBox = new ComboBox<>(FXCollections.observableList(specieService.findAllAdded()));
            try {
                comboBox.valueProperty().bindBidirectional(new JavaBeanObjectPropertyBuilder<Object>().bean(haulBean).name("specie").build());
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            cell.graphicProperty().bind(Bindings.when(cell.emptyProperty()).then((Node) null).otherwise(comboBox));
            return cell;
        }
    });

My table with 3 rows added:

牵引表

Whenever I change one element, it automatically changes all 3.

Looking for solution or guide in the right direction, so that the table looks for each row element as a new HAUL object thus creating new adapter instance for each row.

The individual values for a cell are passed into the cell's updateItem(...) method when the cell needs to display a new value (eg when the cell is initialized, if the property changes, if the cell is reused for a new value, etc). You can control the value that is passed into the cell using the cellValueFactory :

lanSpecie.setCellValueFactory(cellData -> 
    new JavaBeanObjectPropertyBuilder<Specie>()
        .bean(cellData.getValue())
        .name("specie")
        .build());

Having done that, you can get the functionality you need for the cell using the standard ComboBoxTableCell :

lanSpecie.setCellFactory(ComboBoxTableCell.forTableColumn(
    FXCollections.observableList(specieService.findAllAdded()));

The ComboBoxTableCell is doing something like you would get with the following:

lanSpecie.setCellFactory(column -> new TableCell<HAUL, Specie>() {
    private final ComboBox<Specie> comboBox = new ComboBox<>();

    {
        comboBox.setItems(FXCollections.observableList(specieService.findAllAdded()));
        comboBox.setOnAction(e -> commitEdit(comboBox.getValue()));
    }

    @Override
    protected void updateItem(Specie specie, boolean empty) {
        super.updateItem(specie, empty);
        if (empty) {
            setGraphic(null);
        } else {
            comboBox.setValue(specie);
            setGraphic(comboBox);
        }
    }
});

lanSpecie.setOnEditCommit(event -> {
    HAUL haul = event.getRowValue();
    haul.setSpecie(event.getNewValue());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM