PDA

View Full Version : reset jradiobuttton in a group to NULL !!!


tweety_bird_bunny
27-09-2006, 10:40 PM
i created a buttongroup and added 4 jradiobuttons to it initially none selected....
however when i select any one of them on execution of the program,,,
as the buttongroup does,,it requires that atleast one button will always be in ON state....
i want that if i unselect that jradiobutton,,, it shoud be unselected ....

so it means dat if i made selection 1 of the four radiobuttons,,on unselecting it ,, it shud be reset to OFF state....without requring me to select any other button to reset my previous selected button...

tried to use button.setSelected(false) but nothing happens....
plz help me to reset the buttongroup to null somehow

JGuru
28-09-2006, 03:50 PM
@Tweety, In a JRadioButton if you select one(On state), select another( the previous JRadioButton is unselected( Off state),
and present one is selected (On state).
It's called a Toggle. ie., JRadioButton toggles between On & Off state.
Among a group of JRadioButtons only one can be selected
at a time. Also you can't unselect all!! If you want to use a Component where you
can select all or unselect all, you must use JCheckBox

mod-the-pc
28-09-2006, 11:01 PM
Just add another invisible JRadioButton to that ButtonGroup and programatically select it when user clicks on an already selected JRadioButton in the ButtonGroup. This would give an illusion of deselection.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test extends JFrame implements ActionListener
{
JRadioButton jrbArr[]=new JRadioButton[5];
int selected;
public test()
{
super("Test");
ButtonGroup bg=new ButtonGroup();
Container c=getContentPane();
c.setLayout(new GridLayout(5,1));
for(int i=0;i<jrbArr.length;i++)
{
jrbArr[i]=new JRadioButton("Option "+i);
if(i!=0)
{
jrbArr[i].addActionListener(this);
c.add(jrbArr[i]);
}
if(i==0)
{
jrbArr[i].setVisible(false);
jrbArr[i].setSelected(true);
selected=i;
}
bg.add(jrbArr[i]);

}
setSize(352,280);
setVisible(true);
}
public static void main(String arg[])
{
test b=new test();
}
public void actionPerformed(ActionEvent ce)
{
JRadioButton clk=(JRadioButton)ce.getSource();
System.out.println("Previously Selected button : "+jrbArr[selected].getText());
for(int i=1;i<jrbArr.length;i++)
{
if(clk.equals(jrbArr[i]) && selected==i)
{
selected=0;
jrbArr[0].setSelected(true);
}
else if (clk.equals(jrbArr[i]) && selected!=i)
selected=i;
}
}
}