使用 JavaFX 在 TableView 中自动递增不排序

Auto increment in TableView using JavaFX is not sorting

我在 auto numbered table rows (javafx) 中找到了一个 "Simple alternate solution" 用于自动递增值

  1. 这个效果很好。但是,如果我对 table 中的列进行排序,则不会对其进行排序。有什么解决办法吗?

  2. 另外,如果我在中间删除一行并将table内容写入文件,根据解决方案,行号在table视图中调整但是不在文件中。该行将在文件中删除,但不会调整自动递增的值。请帮忙

如果您想要一个附加到数据对象的永久编号,以便数字与数据对象一起排序,那么您应该创建一个包含编号的数据项。

例如:

public class IdentifiedPerson {
  private IntegerProperty id;
  private ObjectProperty<Person> person;

  public IdentifiedPerson(int id, Person person) {
    this.id = new SimpleIntegerProperty(id);
    this.person = new SimpleObjectProperty<>(person);
  }

  public IntegerProperty idProperty() {
    return id;
  }

  public ObjectProperty<Person> personProperty() {
    return person;
  }
}

那么你的TableView定义为:

private TableView<IdentifiedPerson> table = new TableView<IdentifiedPerson>();

并且您为每个 table 列提供单元格值工厂以提供相关数据(人员 ID 或某些人员属性)。

所以 id/row 数字基本上成为对象模型的一部分。如果您可以直接修改 Person 对象,那么您可以将 id 粘贴在那里,而不是将 person id + person 对象的包装器 class。

无论如何,我认为以上信息将帮助您解决问题。如果没有,或者如果您不能自己想出一个工作示例,请添加一些进一步的评论或编辑问题,也许有人可以为您整理一个示例。