简体   繁体   English

如何在javafx的TableColumn内的复选框上触发onclick事件

[英]How to trigger onclick event on Checkbox inside TableColumn in javafx

I have defined TableColumn with checkbox type like below in Javafx. 我已经用Javafx中的复选框类型定义了TableColumn。

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

Now I need to trigger onclick event(to perform some operation) on any of the checkbox clicked inside TableColumn. 现在,我需要在TableColumn内单击的任何复选框上触发onclick事件(以执行一些操作)。 Is there any way to accomplish this ? 有什么办法可以做到这一点?

Any help is greatly appriciated. 任何帮助都非常有用。

I am using the below custome cell factory to get checkboxes in the tableCell . 我正在使用下面的custome单元工厂来获取tableCell checkboxes You can use the same and have the onClick listener here as well. 您可以使用它们,也可以在此处使用onClick侦听器。 Below is the code: 下面是代码:

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);
    }
}
}

The above cell factory can be applied to the tableColumn as mentioned below. 上面提到的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM