【问题标题】:how to use JRadioButton groups with a model如何将 JRadioButton 组与模型一起使用
【发布时间】:2011-01-04 18:32:10
【问题描述】:

有没有办法将一组 JRadioButtons 与数据模型相关联,以便更容易判断选择了哪个按钮(如果有)?

在理想情况下,我想将一组 N 个单选按钮与一个 enum 类相关联,该类具有一个 NONE 值和一个与每个单选按钮关联的值。

【问题讨论】:

    标签: java swing radio-button jradiobutton


    【解决方案1】:

    我解决了自己的问题,这并不难,所以分享和享受:

    import java.util.EnumMap;
    import java.util.Map;
    import javax.swing.JRadioButton;
    
    public class RadioButtonGroupEnumAdapter<E extends Enum<E>> {
        final private Map<E, JRadioButton> buttonMap;
    
        public RadioButtonGroupEnumAdapter(Class<E> enumClass)
        {
            this.buttonMap = new EnumMap<E, JRadioButton>(enumClass);
        }
        public void importMap(Map<E, JRadioButton> map)
        {
            for (E e : map.keySet())
            {
                this.buttonMap.put(e, map.get(e));
            }
        }
        public void associate(E e, JRadioButton btn)
        {
            this.buttonMap.put(e, btn);
        }
        public E getValue()
        {
            for (E e : this.buttonMap.keySet())
            {
                JRadioButton btn = this.buttonMap.get(e);
                if (btn.isSelected())
                {
                    return e;
                }
            }
            return null;
        }
        public void setValue(E e)
        {
            JRadioButton btn = (e == null) ? null : this.buttonMap.get(e);
            if (btn == null)
            {
                // the following doesn't seem efficient...
                        // but since when do we have more than say 10 radiobuttons?
                for (JRadioButton b : this.buttonMap.values())
                {
                    b.setSelected(false);
                }
    
            }
            else
            {
                btn.setSelected(true);
            }
        }
    }
    

    【讨论】:

    • 怎么用EnumMap
    • 我不明白你的问题;我确实使用了 EnumMap。
    【解决方案2】:

    javax.swing.ButtonGroup 是否与您要查找的内容相符

    http://java.sun.com/javase/6/docs/api/javax/swing/ButtonGroup.html

    【讨论】:

    • 不,因为它处理 ButtonModels。我想要一个处理枚举值的模型。
    猜你喜欢
    • 2015-04-19
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2021-12-20
    • 2021-05-12
    • 2014-02-08
    相关资源
    最近更新 更多