1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
beechy
  • 101
  • 8
  • Sounds like a poor design. Radio buttons are typically used when one and only one item in the group is selected. Perhaps a better design is a single button group with speeds of -40 to +40, or one group for speed (including zero), and another to select left, or right. – FredK May 06 '18 at 20:20
  • Where is your [mcve] demonstrating your problem??? You were asked to post one in your last question: https://stackoverflow.com/questions/49211619/jlabel-positioning-is-not-working. An `MCVE` should be posted with EVERY question. Why should we continue to keep helping when you can't listen to suggestions that have been made in the past??? You were also given a link to the Swing tutorial on the same question. Why did you not look at the tutorial for examples that use the radio button??? Do some basic reading first before posting a question. – camickr May 06 '18 at 21:44

1 Answers1

0

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.

camickr
  • 321,443
  • 19
  • 166
  • 288