看了很多中文资料没找到完善的对javafx tableview控件的完善资料,又苦于没空精读官网资料(毕竟用语晦涩,感觉故意刁难……),本人整理如下:
1.实现单元格文本属性可编辑+可监听
代码如下:
C8.setCellFactory(TextFieldTableCell.forTableColumn());
//c8为你的列名称,自定义
@FXML
public void function1(TableColumn.CellEditEvent<Student,String> value) {
//function1为你在scenebuild中绑定的的该列的onAction名称,自定义
//Student和String为表格的数据对象和数据类型,更具实际情况自定义
TableColumn<Student, String> tc = value.getTableColumn();//获取了正在编辑的列命名为tc
Student std = value.getRowValue();//获取了正在编辑的行
System.out.println(tc.getCellData(std));//打印了正在编辑的单元格的值旧值
System.out.println(value.getNewValue());//打印了正在编辑的单元格的值旧值
}
2.实现单元格comboBox属性可编辑+可监听
options = FXCollections.observableArrayList(
"+2",
"-2",
"小组加分"
);
C9.setCellFactory(tc -> {//combobox定义与监听
ComboBox<String> combo = new ComboBox<String>();
combo.setItems(options);
combo.setEditable(true);
TableCell<Student, String> cell = new TableCell<Student, String>() {
protected void updateItem(String chuzhi, boolean empty) {
super.updateItem(chuzhi, empty);
if (empty) {
setGraphic(null);
} else {
combo.setValue(chuzhi);
setGraphic(combo);
}
}
};
combo.setOnAction(e -> {
int rank = cell.getIndex();//获取正在编辑的单元格所在行序号
String value = combo.getValue();//获取正在编辑的单元格值
//具体监听事件根据需要修改这里只是我的情况,关键的看蓝色字体和注释
if(value.equals(options.get(0)) || value.equals(options.get(1) ))//1 2选项
{
//写自己的选择项功能
}
if(value.equals(options.get(2)))//3选项
{
//写自己的选择项功能
}
});
return cell;
});//注意括号
效果如下