JavaFX - 在TableCell中放置一个控件(如按钮)?

时间:2018-02-09 22:07:50

标签: java javafx tableview javafx-8

我尝试根据表格单元格中的对象将自定义内容构建到JavaFX表中。我的感觉是我可以使用setCellFactory来做到这一点,但我不知所措......

例如

...如果我有一个数据接口:

public interface dbBase { ... }

然后,我的每个数据类型都实现了该接口

public class dbType1 implements dbBase { ... }
public class dbType2 implements dbBase { ... }
public class dbType3 implements dbBase { ... }

然后,在设置我的桌子时,我有......

dataColumn.setCellFactory(data -> {
   // what should I put here?
});

dataColumn是:

TableColumn<dbBase, object> dataColumn;

所以,我的问题是: 如何根据列中对象的类型返回自定义TableViewCell?

1 个答案:

答案 0 :(得分:0)

我无法确定在setCellFactory调用时确定类的类型,所以我决定继承TreeTableCell的子类。这样我就可以在项目更新的任何时候更改GUI。

所以,我的setCellValueFactor和setCellFactory调用现在看起来像这样:

        dataColumn.setCellValueFactory(p -> 
             new SimpleObjectProperty<object>(p.getValue().getValue()));

        dataColumn.setCellFactory(p -> new CustomTreeTableCell());

和CustomTreeTableCell()看起来像这样:

    public class CANESTreeTableCell extends TreeTableCell<dbBase, object> {

    private final Button button;
    private final TextField textField;
    private final CheckBox checkBox;

    private ObservableValue<object> observable;

    public CustomTreeTableCell() {
        this.button = new Button();
        this.textField = new TextField();
        this.checkBox = new CheckBox();
    }

    @Override
    public void updateItem(object item, boolean empty) {
        super.updateItem(item, empty);

        if(empty) {
            setGraphic(null);
        } else {

            final TreeTableColumn<dbBase, object> column = getTableColumn();
            observable = column==null ? null : 
                column.getCellObservableValue(getIndex());

            if(item instanceof dbType1) {
                if(observable != null) {
                    button.textProperty().bind(
                        observable.getValue().getNameProperty());
                } else if (item!=null) {
                    button.setText(item.getName());
                }
                setGraphic(button);
            } else if (item instanceof dbType2) {
                if(checkBox != null) {
                    checkBox.textProperty().bind(
                        observable.getValue().getNameProperty());
                } else if (item!=null) {
                    checkBox.setText(item.getName());
                }
                setGraphic(checkBox);
            } else if (item instanceof dbType3) {
                if(observable != null) {
                    textField.textProperty().bind(
                        observable.getValue().getNameProperty());
                } else if (item!=null) {
                    textField.setText(item.getName());
                }
                setGraphic(textField);
            } else {
                setGraphic(null);
            } 

        }
    }
}