Search code examples
javagwtgwt-celltable

GWT how to inherit EditTextCell and override some methods, f.e.: edit(Context context, Element parent, String value)


This is my implementation of EditTextCell:

public class MyEditTextCell extends EditTextCell {

    @Override
    protected void edit(Context context, Element parent, String value) {
        if (value.equals("")) {
            super.edit(context, parent, value);
        } else {
            clearViewData(context.getKey());
        }
    }
}

I would like to text input to be shown for only for empty cells. IT is why I've override the edit() method. The rest behaviour of oryginal EditTextCell is ok, so I've not changed it.

This unfortunatelly doesn't work. Please help.


Solution

  • The editor in EditTextCell is shown in onBrowserEvent method, so you just need:

    public class MyEditTextCell extends EditTextCell {
        @Override
        public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) {
            if(value == null || value.isEmpty())
                super.onBrowserEvent(context, parent, value, event, valueUpdater);
        }
    }
    

    Remember, to add the FieldUpdater to the column to save the edited value.

    Here you have a full working example with simple table type containing only one String:

    public class MyTableType {
    
        private String value;
    
        public MyTableType(String value) {
            super();
            this.value = value;
        }
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    }
    
    CellTable<MyTableType> table = new CellTable<MyTableType>();
    
    MyEditTextCell cell = new MyEditTextCell();
    
    Column<MyTableType, String> column = new Column<MyTableType, String>(cell) {
        @Override
        public String getValue(MyTableType object) {
            if(object.getValue() == null)
                return "";
            else
                return object.getValue();
        }
    };
    column.setFieldUpdater(new FieldUpdater<MyTableType, String>() {
        @Override
        public void update(int index, MyTableType object, String value) {
            object.setValue(value);
        }
    });
    
    table.addColumn(column, "Value");
    
    ArrayList<MyTableType> values = new ArrayList<MyTableType>();
    values.add(new MyTableType("one"));
    values.add(new MyTableType("two"));
    values.add(new MyTableType("three"));
    values.add(new MyTableType(null));
    values.add(new MyTableType(""));
    table.setRowData(values);
    

    Please, notice that once you edit the cell value to be non-empty, the editor will not be shown after that.