由於@ 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;
}