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:
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 :)
On your first and second point, the reason for the two dimensional array is unknown as it is not your code, but is not necessary at all for the use of JRadioButtons. However it is useful to have all your buttons in some type of array, whether it be an arraylist, or a buttonGroup (swing list for buttons) for checking things with the buttons when an action is called. eg on your 3rd point, this array list would allow you to iterate through and check which buttons have been selected and act accordingly.
The purpose for the action listener is for executing an action when the user clicks on a button. The most general use for this is making it so the user is only allowed to select a certain amount of JRadioButtons or to disable them once they have been selected. eg at a character selection menu.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.