i have a multiple jradiobutton that is inside a for loop and i am trying to put listener on it and this is what i found:
Action listener for multiple radio buttons
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()); } };
i kinda understand it but i still have few clarifications:
- what's the purpose of two dimensional jradiobutton? i mean i kinda see that it is to set a name for the jradiobuttons but as far as my understanding goes, it's only for display. yes to confirm that that is the jradiobutton you've selected but i don't get what's the purpose of it in putting actionlistener
- is the two dimensional jradiobutton really that necessary?
- can i just use the name of jradiobuttons
to do something like this:
if(NameOfJRadioButton.isSelected())
{
//some procedures
}
^(i can't seem to convert that into code :/)
if so, how can i do it? or do you have any other suggestions on how to put listener for multiple jradiobuttons? thank you for any of your suggestions :)