how to use JRadioButton groups with a model

℡╲_俬逩灬. 提交于 2020-01-02 07:14:08

问题


Is there any way to associate a group of JRadioButtons with a data model so it is easier to tell which button (if any) is selected?

In an ideal world, I would like to associate a group of N radiobuttons with an enum class that has a NONE value and one value associated with each radiobutton.


回答1:


I solved my own problem, this wasn't too hard, so share and enjoy:

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);
        }
    }
}



回答2:


Is the javax.swing.ButtonGroup on the lines of what you're looking for

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



来源:https://stackoverflow.com/questions/2059122/how-to-use-jradiobutton-groups-with-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!