beechy
beechy

Reputation: 111

Clear Selection of RadioButtons

My application: user wants the object to move left with a particular speed - he/she chooses one radiobutton from moveToLeft ButtonGroup. But he/she changes his/her mind and wants the object to move right - he/she chooses one radiobutton from moveToRight ButtonGroup. My question is - how to clear buttongroup, that was chosen as first. I tried ClearSelection and setSelected(false), but it does not work. Here is my code:

            JRadioButton vel1 = new JRadioButton("10 km/h");
            JRadioButton vel2 = new JRadioButton("20 km/h");
            JRadioButton vel3 = new JRadioButton("30 km/h");
            JRadioButton vel4 = new JRadioButton("40 km/h");

            ButtonGroup moveToRight = new ButtonGroup();
            moveToRight.add(vel1);
            moveToRight.add(vel2);
            ButtonGroup moveToLeft = new ButtonGroup();
            moveToLeft.add(vel3);
            moveToLeft.add(vel4);

            if(vel1.isSelected() || vel2.isSelected() )
            {
                moveToLeft.clearSelection();
                //vel3.setSelected(false);
                //vel4.setSelected(false);
            }
            if(vel3.isSelected() || vel4.isSelected() )
            {
                moveToRight.clearSelection();
                //vel1.setSelected(false);
                //vel2.setSelected(false);
            }

The ButtonGroups are in two different panels.

Upvotes: 1

Views: 1138

Answers (1)

camickr
camickr

Reputation: 324197

What doesn't work? If the clearSelection(...) statement is executed, then it will work. If it doesn't work, then the statement is not executed.

The code you posted won't do anything. That code will be executed when the buttons are created and the frame isn't even visible yet, so obviously they will not yet be selected by the user.

...he/she chooses one radiobutton...

So then you need to add an ActionListener to the radio button to execute the relevant code.

Read the section from the Swing tutorial on How to Use Radio Buttons for more information and working examples.

Upvotes: 0

Related Questions