艰辛啊,在网上找了不少关于JavaFx2.0 中在表格中使用单选框的例子。
我自己没有使用fxml来配置,所以有些例子都用不上。其实,是非常简单的,下面上代码
设定该列的单元格类型为:单选框。CheckBoxTableCell这个类在javafx.scene.control.cell.CheckBoxTableCell包中设定之后,显示的画面就是一个CheckBox了
TableColumn checkBoxColumn = new TableColumn("勾选"); //选中框\
checkBoxColumn.setCellFactory(CheckBoxTableCell.forTableColumn(checkBoxColumn));
接下来头疼就是勾选之后怎么获取值了,研究了半天,网上很多都是自己写一个Cell来处理。
我想了一下应该不用啊,都能使用Property机制了为啥还自己写呢,于是尝试了一下,下面列出几个与网上例子不同的改变点
1. Property所需要的bean,其中对应CheckBox的那个不能再是SimpleStringProperty了,要改换成SimpleBooleanProperty自然下面的get/set方法也要改变
private SimpleStringProperty discription = new SimpleStringProperty(); // 备注
private SimpleBooleanProperty gouxuan = new SimpleBooleanProperty(); //是否选中
public String getDiscription() {
return discription.get();
}
/**
* @return the discription
*/
public SimpleStringProperty discriptionProperty() {
return discription;
}
/**
* @param discription the discription to set
*/
public void setDiscription(String discription) {
this.discription.set(discription);
}
public boolean getGouxuan() {
return gouxuan.get();
}
/**
* @return the discription
*/
public SimpleBooleanProperty gouxuanProperty() {
return gouxuan;
}
/**
* @param discription the discription to set
*/
public void setGouxuan(boolean gouxuan) {
this.gouxuan.set(gouxuan);
}
这样一旦选中不选中,在后面通过tbView.getItems()就可以获取到对象,直接使用对象的get方法就可以拿到值了。
// 设定映射
ObservableList<TableColumn> obserList = tbView.getColumns();
obserList.get(0).setCellValueFactory(new PropertyValueFactory("gouxuan"));
obserList.get(1).setCellValueFactory(new PropertyValueFactory("campusName"));