Java using one ActionListener for multiple radio buttons

I have six switches on the panel, and I would like to listen to the mouse click on the panel, then determine which radio button is selected and perform the corresponding action.

But when I fixed this situation and tried it, with a breakpoint in the action listener, the code does not seem to call the action listener at all. Any explanation of why this is, or an alternative way to avoid writing action listeners for each button, would be greatly appreciated.

Thanks in advance for any advice.

John doner

+4
source share
2 answers

Radio buttons swallow an event and never contribute it to JPanel. If you want to know which button was pressed, you need to add an action listener to each of the buttons. Look at the trace when using the radio buttons

+2
source

This code will add lists cyclically and programmatically.

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; public class Test { public Test() { JFrame frame = new JFrame(); JPanel panel = new JPanel(); ButtonGroup bg = new ButtonGroup(); for (int i = 0; i < 6; i++) { JRadioButton rb = new JRadioButton(); // ID of Button rb.setActionCommand("button " + i); try { //method to call, after pressed a button Method m = getClass() .getDeclaredMethod("RadioButton" + (i+1), null); ActionListener al = new MyActionListener(m, this); rb.addActionListener(al); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } // bg.add(rb); panel.add(rb); } frame.setContentPane(panel); frame.setVisible(true); frame.pack(); } /*buttons actions*/ public void RadioButton1() { System.out.println("Boton1"); } public void RadioButton2() { System.out.println("Boton2"); } public void RadioButton3() { System.out.println("Boton3"); } public void RadioButton4() { System.out.println("Boton4"); } public void RadioButton5() { System.out.println("Boton5"); } public void RadioButton6() { System.out.println("Boton6"); } public static void main(String[] args) { new Test(); } class MyActionListener implements ActionListener { Method call = null; Object object; public MyActionListener(Method m, Object value) { call = m; object = value; } @Override public void actionPerformed(ActionEvent e) { try { //call method call.invoke(object, null); } catch (IllegalArgumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InvocationTargetException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } 
+5
source

Source: https://habr.com/ru/post/1333203/


All Articles