JavaFX TableView与简单的xml模型

问题描述 投票:0回答:1

对于配置,我使用简单的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());
}

javafx tableview simple-framework
1个回答
1
投票

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

你错了。事实上,TableView永远无法访问存储在其物品的BooleanProperty字段中的active对象。

PropertyValueFactory使用反射

  1. 通过使用与"Property"连接的构造函数参数调用方法来访问属性对象。 (在您的情况下,此方法将被称为activeProperty())。
  2. 如果上述方法不起作用,它将包含ObservableValue中属性的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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.