how to use JRadioButton groups with a model(如何将 JRadioButton 组与模型一起使用)
问题描述
有没有办法将一组 JRadioButtons 与数据模型相关联,以便更容易判断选择了哪个按钮(如果有)?
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?
在理想情况下,我想将一组 N 个单选按钮与一个 enum
类相关联,该类具有一个 NONE
值和一个与每个单选按钮关联的值.
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.
推荐答案
我自己解决了这个问题,这并不难,所以分享和享受:
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);
}
}
}
这篇关于如何将 JRadioButton 组与模型一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 JRadioButton 组与模型一起使用
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01