由于@ James_D的例子不再运行,由于链接腐烂,我正在处理这个同样的问题,这是我如何才能创造这种效果。
View the full test case here.
我延伸内建ComboBoxTableCell<S, T>
以暴露必要的字段。自定义TableCell
有一个Supplier<S> tableValue = (S) this.getTableRow().getItem();
用于访问适用的数据对象。此外,我反射性地检索并存储对单元格ComboBox
的引用。因为它在超类中被懒惰地实例化了,所以我也必须在反射之前通过反射来设置它。最后,我必须初始化ComboBox
为好,因为这将是在javafx.scene.control.cell.CellUtils.createComboBox
,因为我手动创建。公开这些信息很重要,如下所示:
在列的CellFactory中,我们完成初始化ComboBoxCell。我们只需要创建一个我们自定义的ComboBoxTableCell
的新实例,然后当第一次显示组合框(例如,我们可以确定我们有一个与单元格关联的数据对象)时,我们将ComboBox#itemsProperty
绑定到Bindings.When
,正确的ObservableList
为案件。
CellFactory:
column1.setCellFactory(c -> {
TransparentComboBoxTableCell<Data, Enum> tcbtc = new TransparentComboBoxTableCell<>();
tcbtc.comboBox.setOnShown(e -> {
if (!tcbtc.comboBox.itemsProperty().isBound()) tcbtc.comboBox.itemsProperty().bind(
Bindings.when(tcbtc.tableValue.get().base.isEqualTo(BASE.EVEN)).then(evens).otherwise(
Bindings.when(tcbtc.tableValue.get().base.isEqualTo(BASE.ODD)).then(odds).otherwise(
FXCollections.emptyObservableList()
))
);
});
return tcbtc;
});
定制ComboBoxTableCell:
public static class TransparentComboBoxTableCell<S, T> extends ComboBoxTableCell<S, T> {
public TransparentComboBoxTableCell() {
this(FXCollections.observableArrayList());
}
public TransparentComboBoxTableCell(ObservableList<T> startingItems) {
super(startingItems);
try {
Field f = ComboBoxTableCell.class.getDeclaredField("comboBox");
f.setAccessible(true);
f.set(this, new ComboBox<>());
comboBox = (ComboBox<T>) f.get(this);
// Setup out of javafx.scene.control.cell.CellUtils.createComboBox
// comboBox.converterProperty().bind(converter);
comboBox.setMaxWidth(Double.MAX_VALUE);
comboBox.getSelectionModel().selectedItemProperty().addListener((ov, oldValue, newValue) -> {
if (this.isEditing()) {
this.commitEdit((T) newValue);
}
});
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
throw new Error("Error extracting 'comboBox' from ComboBoxTableCell", ex);
}
tableValue =() -> (S) this.getTableRow().getItem();
}
public final ComboBox<T> comboBox;
public final Supplier<S> tableValue;
}