Friday, June 19, 2015

GWT - ListBox with Enum vs ValueListBox implementation example


public class EnumListBoxEditor<T extends Enum<T>> implements IsWidget, LeafValueEditor<T> {

    private ListBox listBox;    private Class<T> enumType;
    public EnumListBoxEditor(Class<T> tClass) {
        listBox = new ListBox();        this.enumType = tClass;        for(T e : enumType.getEnumConstants()) {
            listBox.addItem(e.name());        }
    }

    @Override    public Widget asWidget() {
        return listBox;    }

    @Override    public void setValue(T language) {
        listBox.setSelectedIndex(language.ordinal());    }

    @Override    public T getValue() {
        int index = listBox.getSelectedIndex();        T result = null;        for (T e : enumType.getEnumConstants()) {
            String itemName = listBox.getValue(index);            if (e.name().equals(itemName)) {
               result = e;            }
        }
        return result;    }

    public void setEnabled(boolean isEnabled){
        listBox.setEnabled(isEnabled);    }

}

Thus this approach is acceptable the best way to use ListBox with any Enum or bean that implement HasLabel interface is ValueListBox component e.g.:

@UiField(provided = true)
ValueListBox<TeamDTO> team;
 
this.team = new ValueListBox<TeamDTO>(new HasLabelRenderer<TeamDTO>(), new IdentityProvidesKey<TeamDTO>());
 
public class HasLabelRenderer<T extends HasLabel> extends AbstractRenderer<T>{

    @Override    public String render(HasLabel object) {
        return object == null ? "" : object.getLabel();    }

}
 
public class IdentityProvidesKey<T extends Identity> implements ProvidesKey<T> {
    @Override    public Object getKey(T item) {
        return item == null ? null: item.getId();    }
}

No comments: