艱辛啊,在網上找了不少關于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);
}
2. 下一步與網上一樣,綁定到表格上就可以了
這樣一旦選中不選中,在後面通過tbView.getItems()就可以擷取到對象,直接使用對象的get方法就可以拿到值了。
// 設定映射
ObservableList<TableColumn> obserList = tbView.getColumns();
obserList.get(0).setCellValueFactory(new PropertyValueFactory("gouxuan"));
obserList.get(1).setCellValueFactory(new PropertyValueFactory("campusName"));