Thursday, May 7, 2015

GWT - LeafValueEditor implementation for RadioButton widget with Enum type

package com.paniov.bitwitwebapp.client.widgets.editors;

import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.uibinder.client.UiConstructor;
import org.gwtbootstrap3.client.ui.RadioButton;
import org.gwtbootstrap3.client.ui.html.Div;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Paniov on 06.05.15.
 */
public class EnumRadiobuttonEditor extends Div implements LeafValueEditor<ButtonsType> {


    private Map<RadioButton, ButtonsType> map;

    @UiConstructor
    public EnumRadiobuttonEditor(String groupName) {
        map = new HashMap<RadioButton, ButtonsType>();
        for (ButtonsType e: ButtonsType.class.getEnumConstants()){
            RadioButton rb = new RadioButton(groupName, e.name());
            map.put(rb, e);
            super.add(rb);
        }
    }

    @Override
    public void setValue(ButtonsType value) {
        if (value==null)
            return;
        RadioButton rb = (RadioButton) super.getWidget(value.ordinal());
        rb.setValue(true);
    }

    @Override
    public ButtonsType getValue() {
        for (Map.Entry<RadioButton, ButtonsType> e: map.entrySet()) {
            if (e.getKey().getValue())
                return e.getValue();
        }
        return null;
    }
}


========== RadioButton component in UiBinder ==============

            <b:Row>
                <b:Column size="XS_12">
                    <editor:EnumRadiobuttonEditor ui:field="type" />
                    <b:Button ui:field="save" text="Save"/>
                    <b:Label ui:field="label" />
                </b:Column>
            </b:Row>


========= View Impl ==========

@UiField(provided=true)
EnumRadiobuttonEditor type;


type = new EnumRadiobuttonEditor("rButtons");

    @UiHandler("save")
    void onSave(ClickEvent e) {
        MockBean newBean = driver.flush();
        label.setText(newBean.toString());
    }

No comments: