如何使 TableCell 可编辑,使其自动更新数据class?

How to make TableCell editable , so it automatically updates the data class?

我正在为一个学校项目制作一个系统,其中一部分是 TableView,其中使用我自己的数据 class InventoryData 填充了具有相应属性的行到 table 列。我想使用 TextField 在某些列 editable 中创建单元格,以便在提交编辑时,它将更新 InventoryData 对象的相关 属性。

我尝试将 TextFieldTableCell.forTableColumn() 设置为列的细胞工厂。虽然现在在提交编辑后,单元格中的文本会发生变化,但我认为它不会更改 InventoryData 对象中的 属性。我之所以这么认为,是因为当我尝试再次编辑该单元格时(在已经编辑过一次之后),TextField 显示了之前的值(在第一次编辑之前)。

我是不是做错了什么,或者这是正常行为,我必须自己实施提交?

这是 InventoryData 的代码:

package UILayer.TableData;

import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import ModelLayer.Product;

public class InventoryData {


    // From Product
    private Product productObj;
    private SimpleIntegerProperty id;
    private SimpleStringProperty name;

    // Constructor - converts Product obj into InventoryData
    public InventoryData(Product product) 
    {
        this.productObj = product;

        this.id = new SimpleIntegerProperty(product.getId());
        this.name = new SimpleStringProperty(product.getName())

    }


    // GET & SET
    public Product getProduct() 
    {
        return productObj;
    }

    public int getId() {
        return id.get();
    }
    public void setId(int id) {
        this.id.set(id);
    }

    public String getName() {
        return name.get();
    }
    public void setName(String name) {
        this.name.set(name);
        productObj.setName(name);
        System.out.println(productObj.getName());
    }

}

您需要 InventoryData class 才能使用 JavaFX Properties pattern。具体来说,它需要 属性 类型的访问器方法才能检索 table 单元格中的 属性。如果没有这个,单元格值工厂只是调用标准的 getName()getId() 方法,并将结果包装在 ReadOnlyStringWrapper(或 ReadOnlyIntegerWrapper)中:table单元格无法更改这些包装器的值(因为它们是只读的)。

public class InventoryData {


    // From Product
    private Product productObj;
    private IntegerProperty id;
    private StringProperty name;

    // Constructor - converts Product obj into InventoryData
    public InventoryData(Product product) 
    {
        this.productObj = product;

        this.id = new SimpleIntegerProperty(product.getId());
        this.name = new SimpleStringProperty(product.getName())

        this.name.addListener((obs, oldName, newName) -> 
            productObj.setName(newName));

    }


    // GET & SET
    public Product getProduct() 
    {
        return productObj;
    }

    public IntegerProperty idProperty() {
        return id ;
    }
    public final int getId() {
        return idProperty().get();
    }
    public final void setId(int id) {
        idProperty().set(id);
    }

    public StringProperty nameProperty() {
        return name ;
    }
    public final String getName() {
        return nameProperty().get();
    }
    public final void setName(String name) {
        this.nameProperty().set(name);
        // productObj.setName(name);
        // System.out.println(productObj.getName());
    }

}