如何在JavaFX中将CheckBox添加到TableView [英] How to add CheckBox's to a TableView in JavaFX

查看:1220
本文介绍了如何在JavaFX中将CheckBox添加到TableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Java桌面应用程序中,我有一个TableView,其中我想有一个列与复选框。

In my Java Desktop Application I have a TableView in which I want to have a column with CheckBoxes.

我发现这里已经完成http://www.jonathangiles.net/javafx/2.0/CellFactories/ ,但由于下载不可用,因为我不知道乔纳森·吉尔斯会怎么回答我的电子邮件,我想我会问...

I did find where this has been done http://www.jonathangiles.net/javafx/2.0/CellFactories/ but as the download is not available and because I don't know how soon Jonathan Giles will answer my email I thought I'd ask...

如何将CheckBox放在TableView的单元格中? p>

How do I put a CheckBox in a cell of my TableView?

推荐答案

您需要在TableColumn上设置CellFactory。

You need to set a CellFactory on the TableColumn.

Callback<TableColumn<TableData, Boolean>, TableCell<TableData, Boolean>> booleanCellFactory = 
            new Callback<TableColumn<TableData, Boolean>, TableCell<TableData, Boolean>>() {
            @Override
                public TableCell<TableData, Boolean> call(TableColumn<TableData, Boolean> p) {
                    return new BooleanCell();
            }
        };
        active.setCellValueFactory(new PropertyValueFactory<TableData,Boolean>("active"));
        active.setCellFactory(booleanCellFactory);

class BooleanCell extends TableCell<TableData, Boolean> {
        private CheckBox checkBox;
        public BooleanCell() {
            checkBox = new CheckBox();
            checkBox.setDisable(true);
            checkBox.selectedProperty().addListener(new ChangeListener<Boolean> () {
                public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                    if(isEditing())
                        commitEdit(newValue == null ? false : newValue);
                }
            });
            this.setGraphic(checkBox);
            this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            this.setEditable(true);
        }
        @Override
        public void startEdit() {
            super.startEdit();
            if (isEmpty()) {
                return;
            }
            checkBox.setDisable(false);
            checkBox.requestFocus();
        }
        @Override
        public void cancelEdit() {
            super.cancelEdit();
            checkBox.setDisable(true);
        }
        public void commitEdit(Boolean value) {
            super.commitEdit(value);
            checkBox.setDisable(true);
        }
        @Override
        public void updateItem(Boolean item, boolean empty) {
            super.updateItem(item, empty);
            if (!isEmpty()) {
                checkBox.setSelected(item);
            }
        }
    }

这篇关于如何在JavaFX中将CheckBox添加到TableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆