javafx TableValue 新增按鈕列,以及刪除列功能
阿新 • • 發佈:2019-02-03
首先需要自定義一個TableCell
import javafx.beans.value.ObservableValue; import javafx.scene.control.CheckBox; import javafx.scene.control.TableCell; /** * * @author Administrator */ public class CheckBoxButtonTableCell<S, T> extends TableCell<S, T> { private final CheckBox chebox; private ObservableValue<T> ov; public CheckBoxButtonTableCell() { this.chebox = new CheckBox(); //新增元素 setGraphic(chebox); } @Override protected void updateItem(T item, boolean empty) { System.out.println("empty:"+empty); super.updateItem(item, empty); if (empty) { //如果此列為空預設不新增元素 setText(null); setGraphic(null); } else { //初始化為不選中 chebox.setSelected(false); setGraphic(chebox); } } }
然後需要繫結列為複選框
isCheck.setCellValueFactory(new PropertyValueFactory<Person, Boolean>( "isCheck")); isCheck.setCellFactory(new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() { public TableCell<Person, Boolean> call( TableColumn<Person, Boolean> param) { final CheckBoxButtonTableCell<Person, Boolean> cell = new CheckBoxButtonTableCell<>(); final CheckBox checkbox = (CheckBox) cell .getGraphic(); checkbox.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent event) { System.out.println("進來了"); Person person = personData.get(cell.getIndex()); if(person.getIsCheck()){ person.setIsCheck(false); }else{ person.setIsCheck(true); } } }); return cell; } });
然後是刪除功能,如果選中了則刪除該列
@FXML public void delPerson(){ int i = 0; for(Person person:Person.personList){ if(person.getIsCheck()==true){ Person.personList.remove(i); delPerson(); break; } i++; } findPersonList(); }
程式碼地址:https://git.oschina.net/ndsg/JavaFxSample