使用javafx tableview控件時徹底解決單元格可編輯且可監聽

看了很多中文資料沒找到完善的對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;
                    
});//注意括號

效果如下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章