001    package org.springframework.richclient.form.binding.swing;
002    
003    import java.util.ArrayList;
004    import java.util.List;
005    import java.util.Map;
006    
007    import javax.swing.JComponent;
008    import javax.swing.JPanel;
009    
010    import org.springframework.binding.form.FormModel;
011    import org.springframework.richclient.form.binding.Binding;
012    import org.springframework.richclient.form.binding.support.AbstractBinder;
013    
014    /**
015     * Radio button binder for enum values.
016     *
017     * Use this in your Application Context to configure the binder:
018     *
019     * <pre>
020     * &lt;bean name="enumRadioButtonBinder" class="org.springframework.richclient.form.binding.swing.EnumRadioButtonBinder" /&gt;
021     * </pre>
022     *
023     * Or when you need an additional null value that can be selected:
024     *
025     * <pre>
026     * &lt;bean name="enumRadioButtonBinder" class="org.springframework.richclient.form.binding.swing.EnumRadioButtonBinder" &gt;
027     *     &lt;property name="nullable" value="true" /&gt;
028     * &lt;/bean&gt;
029     * </pre>
030     *
031     * @author Lieven Doclo
032     */
033    public class EnumRadioButtonBinder extends AbstractBinder {
034    
035        private boolean nullable = false;
036    
037        /**
038         * Creates a new binder
039         */
040        public EnumRadioButtonBinder() {
041            super(Enum.class);
042        }
043    
044        @Override
045        protected JComponent createControl(Map context) {
046            return new JPanel();
047        }
048    
049        /**
050         * Sets whether this control can contain a <code>null</code> value
051         *
052         * @param nullable <code>true</code> if the binder needs to contain a
053         * <code>null</code> value
054         */
055        public void setNullable(boolean nullable) {
056            this.nullable = nullable;
057        }
058    
059        @Override
060        protected Binding doBind(JComponent control, FormModel formModel, String formPropertyPath, Map context) {
061            EnumRadioButtonBinding binding = new EnumRadioButtonBinding((JPanel) control, formModel, formPropertyPath,
062                    getPropertyType(formModel, formPropertyPath), getSelectableEnumsList(formModel, formPropertyPath));
063            return binding;
064    
065        }
066    
067        /**
068         * Adds the <code>null</code> value if this binder is nullable.
069         */
070        private List<Enum> getSelectableEnumsList(FormModel formModel, String formPropertyPath) {
071            List<Enum> out = new ArrayList<Enum>();
072            if (nullable) {
073                out.add(null);
074            }
075            for (Enum e : ((Class<Enum>) getPropertyType(formModel, formPropertyPath)).getEnumConstants()) {
076                out.add(e);
077            }
078            return out;
079        }
080    
081    }