java-如何在模型中使用JRadioButton组
作者:互联网
有没有什么方法可以将一组JRadioButton与数据模型相关联,以便更容易判断选择了哪个按钮(如果有)?
在理想的世界中,我想将一组N个单选按钮与一个枚举类相关联,该枚举类具有NONE值和与每个单选按钮相关联的一个值.
解决方法:
我解决了自己的问题,这并不难,所以分享并享受:
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);
}
}
}
标签:jradiobutton,swing,java,radio-button 来源: https://codeday.me/bug/20191210/2100996.html