Javafx TableView具有简单的XML模型



用于配置i使用简单XML。我还将此模型用于tableview。我的问题是使用布尔。TableView显然需要BooleanProperty,但简单的XML无法访问此对象。我如何在不编写大型代码的情况下结合使用?

模型

@Root(name="scriptdata")
@Order(elements={"title", "active"})
public class ScriptData {
    @Element (required=true)
    private String title;
    @Element (required=false)
    private BooleanProperty active;
    /**
     *
     * @param title
     * @param active
     */
     public ScriptData() {
        this.active = new SimpleBooleanProperty(active);
     }

    public boolean isActive() {
        return active.getValue();
    }
    public void setActive(boolean active) {
        this.active.set(active);
    }

CellFactory

modulActiveColumn.setCellValueFactory(new PropertyValueFactory<>("active"));
modulActiveColumn.setCellFactory(CheckBoxTableCell.forTableColumn(modulActiveColumn));
modulActiveColumn.setOnEditCommit((EventHandler<CellEditEvent>) t -> {
    ((ScriptData) t.getTableView().getItems().get(
      t.getTablePosition().getRow())
      ).setActive((boolean) t.getNewValue());
}

我的问题是使用布尔值。TableView需要BooleanProperty

你错了。实际上,TableView永远不会获得对存储在其项目的active字段中的BooleanProperty对象的访问。

PropertyValueFactory使用反射为

  1. 通过使用与"Property"串联的构造函数参数调用方法来访问属性对象。(在您的情况下,此方法称为activeProperty())。
  2. 如果上述不起作用,则包含由 ObservableValue中属性的getter返回的值。(在这种情况下,Getter的名称是getActive()isActive)。

在您的情况下, cellValueFactory做类似于以下工厂的事情

modulActiveColumn.setCellValueFactory(cellData -> new SimpleBooleanProperty(cellData.getValue().isActive()));

在您的情况下,使用boolean字段存储数据完全相同。这种方法的缺点是该属性的程序更新不会触发TableView的更新,并且需要手动处理编辑。

@Root(name="scriptdata")
@Order(elements={"title", "active"})
public class ScriptData {
    @Element (required=true)
    private String title;
    @Element (required=false)
    private boolean active;
    /**
     *
     * @param title
     * @param active
     */
    public ScriptData() {
    }
    public boolean isActive() {
        return active;
    }
    public void setActive(boolean active) {
        this.active = active;
    }
}

最新更新