如何将JRadioButton组与模型一起使用
有没有办法将一组JRadioButtons与数据模型相关联,这样就更容易分辨出哪个按钮(如果有的话)被选中了?
在一个理想的世界中,我想将一组N个radiobuttons与一个enum
类相关联,该enum
类具有NONE
值和一个与每个radiobutton相关联的值。
我解决了自己的问题,这不是太难,所以分享和享受:
import java.util.EnumMap; import java.util.Map; import javax.swing.JRadioButton; public class RadioButtonGroupEnumAdapter> { final private Map buttonMap; public RadioButtonGroupEnumAdapter(Class enumClass) { this.buttonMap = new EnumMap(enumClass); } public void importMap(Map 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); } } }
javax.swing.ButtonGroup
是您正在寻找的行
http://java.sun.com/javase/6/docs/api/javax/swing/ButtonGroup.html
- Spring安全性:期望只为类型接口找到一个bean org.springframework.security.authentication.AuthenticationManager
- 解密由.NET的RijndaelManaged使用Java加密的字节
- 使用Java中的ProcessBuilder将进程的输出重定向到另一个进程的输入
- 如何在Hadoop中将String对象转换为IntWritable对象
- 亚利桑那州TimeZone日节省光
- 关于@ ForceDiscriminator / @ DiscriminatorOptions(force = true)的使用
- 为什么不允许接口作为注释成员?
- 创建对象而不会导致堆栈溢出错误?
- 如何在Gmail中获取完整的邮件正文?