【问题标题】:TableCell focusedProperty listener not called when inheriting from TextFieldTableCell从 TextFieldTableCell 继承时未调用 TableCellfocusedProperty 侦听器
【发布时间】:2014-09-26 18:15:45
【问题描述】:

我想创建一个 Cell 工厂,它返回一个行为与 TextFieldTableCell 完全相同的 TableCell,但有以下区别:当它失去焦点时,它会提交更改。

我的代码很简单:

public final class TextFieldCellFactory<S, T> implements Callback<TableColumn<S, T>, TableCell<S, T>> {

    @Override
    public TableCell<S, T> call(TableColumn<S, T> p) {

        class EditingCell extends TextFieldTableCell {

            public EditingCell() {

                super();

                setConverter(new DefaultStringConverter());

                focusedProperty().addListener(new ChangeListener() {

                    @Override
                    public void changed(ObservableValue observable, Object oldValue, Object newValue) {

                        System.out.println("changed!");

                        System.out.println("getText() = " + getText());
                        System.out.println("textProperty() = " + textProperty().get());
                        System.out.println("getItem = " + getItem());
                    }
                });
            }

            @Override
            public void startEdit() {

                super.startEdit();
            }

            @Override
            public void cancelEdit() {

                super.cancelEdit();
            }

        }

        return new EditingCell();
    }
}

如您所见,我在focusedProperty 中添加了一个更改监听器。问题是没有调用 change 方法(没有打印任何内容)。

如何获得所需的行为?谢谢。

【问题讨论】:

    标签: javafx-8


    【解决方案1】:

    基本上,您必须使用 textField(不是单元格的)focusedProperty 注册侦听器。由于 textfield 是 super 的私有字段,因此不能直接访问 - 您必须在将其添加到单元格后查找一次。那是第一次开始编辑的时候:

    private TextField myTextField;
    
    @Override
    public void startEdit() {
        super.startEdit();
        if (isEditing() && myTextField == null) {
            // most simple case, assuming that there is no graphic other than the field 
            // TBD: implement the general case: walk the tree and find the field
            myTextField = (TextField) getGraphic();
            myTextField.focusedProperty().addListener((e, old, nvalue) -> {
                if (!nvalue) {
                    T edited = getConverter().fromString(myTextField.getText());
                    commitEdit(edited);
                }
    
            });
        }
    }
    

    一些注意事项:

    • 这是围绕open issue 的解决方法(投赞成票!)
    • 从 jdk8 开始,不是entirely functional:如果单击表格内的其他位置,将不会提交
    • recent answer 使用的绑定方法可能功能齐全,也可能不完全(未测试)

    【讨论】:

    • 我找到了解决方案 - 看看这篇文章中的第一个答案:stackoverflow.com/questions/23632884/…
    • @user92834 你的答案是我在笔记的最后一个项目符号中引用的:-) 无论如何,它的行为有点古怪 - 请参阅我对你的答案的评论。
    猜你喜欢
    • 2012-04-30
    • 2019-07-25
    • 2019-01-26
    • 1970-01-01
    • 2012-04-08
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多