通常,需要与所选单选按钮关联的某些对象。它不一定String
代表按钮的标签。它可以是Integer
包含按钮的索引的对象,也可以是更复杂类型的对象T
。您可以Map<ButtonModel, T>
按照Tom Hawtin的建议填充和使用,但是我建议扩展模型并将对象放置在那里。这ButtonGroup
是使用此方法的改进。
import javax.swing.*;
@SuppressWarnings("serial")
public class SmartButtonGroup<T> extends ButtonGroup {
@Override
public void add(AbstractButton b) {
throw new UnsupportedOperationException("No object supplied");
}
public void add(JRadioButton button, T attachedObject) {
ExtendedModel<T> model = new ExtendedModel<>(attachedObject);
model.setSelected(button.isSelected());
button.setModel(model);
super.add(button);
}
@SuppressWarnings("unchecked")
public T getSelectedObject() {
ButtonModel selModel = getSelection();
return selModel != null ? ((ExtendedModel<T>)selModel).obj : null;
}
public static class ExtendedModel<T> extends javax.swing.JToggleButton.ToggleButtonModel {
public T obj;
private ExtendedModel(T object) {
obj = object;
}
}
}
您可以使用此实用程序类代替ButtonGroup
。创建此类的对象,并向其添加按钮和关联的对象。例如,
SmartButtonGroup<Integer> group = new SmartButtonGroup<>();
JPanel panel = new JPanel();
for (int i = 1; i <= 5; i++) {
JRadioButton button = new JRadioButton("Button #" + i, i == 3);
group.add(button, i);
panel.add(button);
}
之后,只需调用即可随时获取与当前所选按钮关联的对象getSelectedObject()
,如下所示:
int selectedButtonIndex = group.getSelectedObject();
如果只需要按钮本身,则可以使用下一个非泛型类。
import javax.swing.JRadioButton;
@SuppressWarnings("serial")
public class RadioButtonGroup extends SmartButtonGroup<JRadioButton> {
public void add(JRadioButton button) {
super.add(button, button);
}
@Override
public void add(JRadioButton button, JRadioButton attachedObject) {
throw new UnsupportedOperationException("Use the short form of addition instead");
}
public JRadioButton getSelectedButton() {
return getSelectedObject();
}
}