我正在尝试将 Combo Box
添加到我的 Table View
:
基本上我有一个名为 TableViewTest 的类,它存储名称和描述,我可以在 Table View
中显示这些名称和描述 --- 不用麻烦,但我想做的是添加第三列,每个单元格都有一个 Combo Box
以便用户可以从每个人的多个选项中选择一个。
到目前为止,我已经创建了一个 ObservableList
类型 String
具有一些值并将它们添加到 ComboBox
对象。有谁知道我可以将这个 Combo Box
添加到表中的方法吗?
还要记住这段代码非常粗糙,我只是想让一些东西工作,我会在以后重构代码。
ObservableList<TableViewTest> products = FXCollections.observableArrayList();
for(int i = 0; i < b.length; i++){
// random String values
products.add(new TableViewTest(b[i], a[i]));
}
ObservableList<String> options = FXCollections.observableArrayList(
"1",
"2",
"3"
);
final ComboBox comboBox = new ComboBox(options);
TableColumn<TableViewTest, String> nameColumn = new TableColumn<> ("Name");
nameColumn.setMinWidth(200);
nameColumn.setCellValueFactory(new PropertyValueFactory<TableViewTest, String>("name"));
//price Column
//Stock Column
TableColumn<TableViewTest, String> StockColumn = new TableColumn<> ("Stock");
StockColumn.setMinWidth(150);
StockColumn.setCellValueFactory(new PropertyValueFactory<TableViewTest, String>("description"));
TableColumn<Object,ComboBox> PriceColumn;
PriceColumn = new TableColumn<>("Source");
PriceColumn.setMinWidth(150);
//PriceColumn.setCellValueFactory(new PropertyValueFactory<>
//(options));
//PriceColumn.setCellFactory(ComboBoxTableCell.forTableColumn(new
//DefaultStringConverter(), options));
//PriceColumn.setCellFactory(ComboBoxTableCell.forTableColumn(
//comboBox));
TableView<TableViewTest> table = new TableView<>();
table.setItems(products);
table.getColumns().addAll(nameColumn, StockColumn, PriceColumn);
原文由 noobCoder 发布,翻译遵循 CC BY-SA 4.0 许可协议
James_D 的回答效果很好,但需要用户单击该项目才能看到
ComboBox
。如果您想在列中始终显示ComboBox
es,则必须使用自定义cellFactory
:例子: