How to get the text value of JRadioButton

Tuhin Bhatt picture Tuhin Bhatt · Nov 22, 2011 · Viewed 16.7k times · Source

I am creating a project in java. My Program has 80 JRadioButtons .... I need the get the text value of them.. Now these radiobuttons are added to ButtonGroup(each has 4 radio buttons)...

I know how to get the text value from the radio button by this following code

radiobutton1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String q1=e.getActionCommand();
                JOptionPane.showMessageDialog(null, q1);
            }
        });

Now is there any easy way to do this? because i will have to do this above code for 80 times(for eighty radiobuttons if i use the above use the above method

Additional Info- I have Total 20 ButtonGroups each with 4 radio buttons. So(80 radio buttons).

Answer

mKorbel picture mKorbel · Nov 22, 2011
I have Total 20 ButtonGroups each with 4 radio buttons. So(80 radio buttons).

then easiest way is

String actionCommand = "";
ButtonModel buttonModel = myButtonGroup.getSelection();
if (buttonModel != null) {
   actionCommand = buttonModel.getActionCommand();
} else {
   // buttonModel is null.
   // this occurs if none of the radio buttons 
   // watched by the ButtonGroup have been selected.
}