我想要的是:如果选择了 ButtonGroup 中包含的 JRadioButton,则创建一个触发的事件,然后打印 JRadioButton 上的文本。
问问题
16460 次
1 回答
14
根据我的评论,您不能将侦听器添加到 ButtonGroup。您可能必须使用添加到单个 JRadioButtons 的 ActionListener。
如果这不能回答您的问题,请告诉我们有关您的问题的更多详细信息。
编辑 1
我想你总是可以扩展ButtonGroup 以便它接受 ActionListeners。例如:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.event.EventListenerList;
@SuppressWarnings("serial")
public class MyButtonGroup extends ButtonGroup {
private ActionListener btnGrpListener = new BtnGrpListener();
private EventListenerList listenerList = new EventListenerList();
@Override
public void add(AbstractButton b) {
b.addActionListener(btnGrpListener);
super.add(b);
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
protected void fireActionListeners() {
Object[] listeners = listenerList.getListenerList();
String actionCommand = "";
ButtonModel model = getSelection();
if (model != null) {
actionCommand = model.getActionCommand();
}
ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, actionCommand);
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]== ActionListener.class) {
((ActionListener)listeners[i+1]).actionPerformed(ae);
}
}
}
private class BtnGrpListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
fireActionListeners();
}
}
}
并通过以下测试:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MyButtonGroupTest {
private static void createAndShowUI() {
String[] data = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
JPanel panel = new JPanel(new GridLayout(0, 1));
MyButtonGroup myBtnGrp = new MyButtonGroup();
myBtnGrp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Action Command is: " + e.getActionCommand());
}
});
for (String text : data) {
JRadioButton radioBtn = new JRadioButton(text);
radioBtn.setActionCommand(text);
myBtnGrp.add(radioBtn);
panel.add(radioBtn);
}
JFrame frame = new JFrame("MyButtonGroupTest");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
但这最终仍然会为每个 JRadioButton 添加 ActionListers 以达到其目的;它只是在 MyButtonGroup 的 add 方法覆盖的幕后执行此操作。
于 2011-07-30T14:20:06.037 回答