Action listener for multiple radio buttons

江枫思渺然 提交于 2019-12-23 04:37:27

问题


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


回答1:


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



回答2:


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();
   ...
}



回答3:


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


来源:https://stackoverflow.com/questions/17653116/action-listener-for-multiple-radio-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!