多个单选按钮的动作侦听器

我打算编写一个程序,让用户可以选择8 * 8矩阵。 因为我的声望低于10,所以我不能包含图像,但请放心,它只是一个普通的8 * 8矩阵。 我计划在我的Java程序中用8 * 8 = 64个单选按钮将其可视化。 用户一次只能选择一个单选按钮,这意味着所有64个按钮将属于同一个按钮组。

现在,我该如何管理动作监听器? 为64个单选按钮中的每一个设置64个独立的动作监听器是不可能的(真的很烦人和无聊)。 因为所有64个单选按钮都在同一个按钮组中,有什么办法可以设置一个事件监听器来检查选择了哪个按钮?

如果我的任何信息不清楚,请告诉我:)

PS :我正在使用Netbeans设计工具

创建二维JRadioButton数组

  JRadioButton[][] jRadioButtons = new JRadioButton[8][]; ButtonGroup bg = new ButtonGroup(); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(8, 8)); for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { JRadioButton btn = new JRadioButton(); btn.addActionListener(listener); btn.setName("Btn[" + i + "," + j + "]"); bg.add(btn); panel.add(btn); // can be used for other operations jRadioButtons[i][j] = btn; } } 

这是所有JRadioButtons的单个ActionListener

  ActionListener listener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JRadioButton btn = (JRadioButton) e.getSource(); System.out.println("Selected Button = " + btn.getName()); } }; 

动作侦听器传递给ActionEvent。 您可以创建一个侦听器,将其绑定到所有按钮,并使用getSource()检查事件源:

 void actionPerformed(ActionEvent e) { Object source = e.getSource(); ... } 

我想你正在实现这样的单选按钮:

 JRadioButton radioButton = new JRadioButton("TEST"); 

如果您这样做,则必须使用以下语句为每个按钮设置ActionListener(例如,在for循环中初始化并设置ActionListener):

radioButton.addActionListener(this) (如果在同一个类中实现ActionListener)

最后你可以转到你的actionPerformed(ActionEvent e)方法并使用e.getSource获取源代码,然后执行if else以获得正确的RadioButton:

 if(e.getSource == radioButton1) { // Action for RadioButton 1 } else if(e.getSource == radioButton2) { // Action for RadioButton 2 } ...