【发布时间】:2016-11-24 01:49:33
【问题描述】:
我想在TableView 中显示以下 ObservableMap:
private ObservableMap<String, Shape> myShapes = FXCollections.observableHashMap();
其中Shape定义如下:
public class Shape {
private StringProperty areaFormula = new SimpleStringProperty();
private IntegerProperty numSides = new SimpleIntegerProperty();
public Shape(String areaFormula, int numSides)
{
this.areaFormula.set(areaFormula);
this.numSides.set(numSides);
}
public String getAreaFormula() { return areaFormula.get(); }
public void setAreaFormula(String areaFormula) { this.areaFormula.set(areaFormula); }
public StringProperty areaFormulaProperty() { return this.areaFormula; }
public int getNumSides() { return numSides.get(); }
public void setNumSides(int sides) { this.numSides.set(sides); }
public IntegerProperty numSidesProperty() { return this.numSides; }
}
我希望 TableView 的第一列是 Map Key(称为 key),第二列是 myShapes.get(key).getAreaFormula(),第三列是 myShapes.get(key).getnumSides()。我希望 TableView 在地图更改时自动更新。
如果可能的话,让用户可以编辑TableView 的第二列和第三列也非常好,这些编辑会在地图中更新。
我已经向 stackoverflow 询问了关于使用 ObservableMap 填充 TableView 以便它会在此处更新更改: Populating a TableView with a HashMap that will update when HashMap changes 。但是,正如您在讨论中看到的那样,它不像我在这里那样处理自定义类。
到目前为止,这是我的解决方案:
ObservableMap<String, Shape> map = FXCollections.observableHashMap();
ObservableList<String> keys = FXCollections.observableArrayList();
map.addListener((MapChangeListener.Change<? extends String, ? extends Shape> change) -> {
boolean removed = change.wasRemoved();
if (removed != change.wasAdded()) {
// no put for existing key
if (removed) {
keys.remove(change.getKey());
} else {
keys.add(change.getKey());
}
}
});
map.put("square", new Shape("L^2", 4));
map.put("rectangle", new Shape("LW", 4));
map.put("triangle", new Shape("0.5HB", 3));
final TableView<String> table = new TableView<>(keys);
TableColumn<String, String> column1 = new TableColumn<>("Key");
column1.setCellValueFactory(cd -> Bindings.createStringBinding(() -> cd.getValue()));
TableColumn<String, String> column2 = new TableColumn<>("Value");
column2.setCellValueFactory( ... );
table.getColumns().setAll(column1, column2);
我卡住的地方是倒数第二行column2.setCellValueFactory( ... )。我希望column2 显示Shape 的getAreaFormula() SimpleStringProperty,但我不知道如何设置CellValueFactory 这样做。
感谢您的帮助。
【问题讨论】: