从TableView获取ComboBox的方法是通过TableCell的getGraphic()方法获取到TableCell中的ComboBox实例。首先,我们需要自定义一个TableCell类,然后在该类中重写updateItem()方法,在该方法中将ComboBox设置为TableCell的图形。接下来,在TableView中,通过调用TableColumn的setCellFactory()方法,将自定义的TableCell类设置为该列的单元格工厂。这样,当TableView中的某一行被选中时,我们就可以通过TableCell的getGraphic()方法获取到该行中的ComboBox实例。
以下是一个示例代码:
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.util.Callback;
public class ComboBoxTableCell<S, T> extends TableCell<S, T> {
private ComboBox<T> comboBox;
public ComboBoxTableCell() {
comboBox = new ComboBox<>();
}
@Override
protected void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(comboBox);
comboBox.setValue(item);
}
}
public static <S, T> Callback<TableColumn<S, T>, TableCell<S, T>> forTableColumn() {
return param -> new ComboBoxTableCell<>();
}
}
然后,在你的代码中,你可以这样使用这个自定义的TableCell类:
TableColumn<Item, String> column = new TableColumn<>("Column");
column.setCellFactory(ComboBoxTableCell.forTableColumn());
这样,TableView中的该列的单元格就会显示为ComboBox,并且你可以通过TableCell的getGraphic()方法获取到ComboBox实例。
没有搜到相关的文章