MD Yousuf Azad
MD Yousuf Azad

Reputation: 13

Action listener for multiple radio buttons

I intend to write a program where I will give the user a choice to choose from a 8*8 matrix. Because my reputation is below 10 I can not include an image but rest assured its just a normal 8*8 matrix. I plan to visualize it in my Java program with 8*8=64 radio buttons. the user can choose only one radio button at a time so it means all 64 buttons will be of the same button group.

Now, how can I manage the action listeners? it is impossible (really tiresome and boring) to set up 64 individual action listener for each of the 64 radio buttons. since all 64 radio buttons are in the same button group, is there any way I can set up only one event listener to check which button is selected?

If any of my given info is unclear then please let me know :)

PS: I am using Netbeans design tools

Upvotes: 0

Views: 15830

Answers (3)

vels4j
vels4j

Reputation: 11298

Create two dimensional JRadioButton array like

        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;
            }
        }

Here is single ActionListener for all JRadioButtons

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

Upvotes: 1

marc3l
marc3l

Reputation: 2605

I think you are implementing the radio buttons like this:

JRadioButton radioButton = new JRadioButton("TEST");

If you are doing like this you have to set a ActionListener to each of your buttons (for example initialize and set the ActionListener in a for-loop) with this statement:

radioButton.addActionListener(this) (if you implement ActionListener in the same class)

At last you can go to your actionPerformed(ActionEvent e) method and get the source with e.getSource and then do something like if else to get the right RadioButton:

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

Upvotes: 0

kiheru
kiheru

Reputation: 6618

The action listener gets passed an ActionEvent. You can make one listener, bind it to all the buttons, and check the event source with getSource():

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

Upvotes: 0

Related Questions