2016-05-23 48 views
0

我已經在Javafx中定義了TableColumn,其類型如下所示。如何觸發javafx中TableColumn內Checkbox的onclick事件

TableColumn<MyObject, Boolean> cbCol = new TableColumn<>(strColName); 
cbCol.setCellFactory(CheckBoxCellFactory.forTableColumn(cbCol)); 

現在我需要在裏面任何的TableColumn點擊複選框的觸發onclick事件(來執行一些操作)。有什麼辦法可以做到這一點?

任何幫助大大appriciated。

回答

0

我使用下面的custome單元工廠在tableCell中獲得checkboxes。您也可以使用相同的方法,並在此處設置onClick偵聽器。下面是代碼:

final class BooleanCell extends TableCell<MyObject, Boolean> { 

private CheckBox checkBox; 

public BooleanCell() { 
    checkBox = new CheckBox(); 
    checkBox.setOnAction((evt) -> { 

     getTableView().getItems().get(getIndex()).setCheck(new SimpleBooleanProperty(checkBox.isSelected())); 

     } 
    }); 
    this.setGraphic(checkBox); 
    this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY); 
    this.setEditable(true); 
} 

@Override 
public void startEdit() { 
    super.startEdit(); 
    if (isEmpty()) { 
     return; 
    } 
    checkBox.requestFocus(); 
} 

@Override 
public void cancelEdit() { 
    super.cancelEdit(); 
//   checkBox.setDisable(true); 
} 

@Override 
public void commitEdit(Boolean value) { 
    super.commitEdit(value); 
//   checkBox.setDisable(true); 
} 

@Override 
public void updateItem(Boolean item, boolean empty) { 
    super.updateItem(item, empty); 
    if (empty) { 
     setGraphic(null); 
    } else { 
     if (item != null) { 
      checkBox.setAlignment(Pos.CENTER); 
      checkBox.setSelected(item); 
     } 
     setAlignment(Pos.CENTER); 
     setGraphic(checkBox); 
    } 
} 
} 

上面cell factory可以如下所述被施加到tableColumn

Callback<TableColumn<MyObject, Boolean>, TableCell<MyObject, Boolean>> booleanCellFactory = new Callback<TableColumn<MyObject, Boolean>, TableCell<MyObject, Boolean>>() { 
       @Override 
       public TableCell<MyObject, Boolean> call(TableColumn<MyObject, Boolean> p) { 
        return new BooleanCell(); 
       } 
      }; 

tbColCheck.setCellFactory(booleanCellFactory);