Niki E. Z.
Niki E. Z.

Reputation: 19

JavaFX TableView update cell, does not update the object value

After making a column editable as a textfield, and being able to edit and update the value shown inside the cell, I noticed that whenever i tried to extract the updated value from the tableview, only the old original unedited value was returned to me - It seems like the value represented inside the cell does not equal to the one returned from the underlying model object.

To make my colum editable i use the following code:

ObservableList<TableColumn> colums = search.getColumns();

colums.get(1).setEditable(true);
colums.get(1).setCellFactory(TextFieldTableCell.<DataPoint>forTableColumn());
colums.get(1).setCellValueFactory(new PropertyValueFactory<DataPoint, String>("No"));

A short snippet of the DataPoint object is as shown below

public class DataPoint {
    private ArrayList<String> data;

    /* Constructor not shown in example */

    // Get Number
    public String getNo() {
        return this.data.get(1);
    }

    public void setNo(String No) {
        this.data.set(1, No);
    }
}

To extract the value of the cell, the following code is used:

DataPoint selectedData = (DataPoint) TableView_Search.getSelectionModel().getSelectedItem();

System.out.println(selectedData.getNo());

So how would I save this updated value inside the model object / how could i extract the shown value inside the cell?

(My GUI is a FXML document made with the Scene Builder program from Gluon)

Upvotes: 1

Views: 4280

Answers (1)

fabian
fabian

Reputation: 82491

Unless the cellValueFactory returns a property that also allows you to write to the item, you need to use the onEditCommit event to store the value in the item. PropertyValueFactory returns a property that does not write to the item, if just the getter and setter but no property getter exists in the item class.

((TableColumn<DataPoint, String>) colums.get(1)).setOnEditCommit(evt -> evt.getRowValue().setNo(evt.getNewValue()));

Alternatively you could use a JavaBeanStringProperty returned from the cellValueFactory to achieve this effect:

JavaBeanStringPropertyBuilder builder = JavaBeanStringPropertyBuilder.create().beanClass(DataPoint.class).name("no");
colums.get(1).setCellValueFactory(cd -> builder.bean(cd.getValue()).build());   

Upvotes: 2

Related Questions