Pergunta

I am developing a Java desktop app.I need to implement gender selection (male or female) using JRadioButton .I have two JRadioButttons .But my problem is that here I can select both JRadioButtons.How can i restrict this ?

that is I need to select only one at a time.

here is my code snippet

     JRadioButton male=new JRadioButton();
     raillabel.add(male);
     male.setBounds(150,152,25,25);
     JRadioButton female=new JRadioButton();
     raillabel.add(female);
     female.setBounds(260,152,25,25);

How can i resolve this issue any idea ?

Foi útil?

Solução

Add them to a ButtonGroup.

ButtonGroup group = new ButtonGroup();
group.add(male);
group.add(female);

From the How to Use Buttons, Check Boxes, and Radio Buttons tutorial:

For each group of radio buttons, you need to create a ButtonGroup instance and add each radio button to it. The ButtonGroup takes care of unselecting the previously selected button when the user selects another button in the group.

You should generally initialize a group of radio buttons so that one is selected. However, the API doesn't enforce this rule — a group of radio buttons can have no initial selection. Once the user has made a selection, exactly one button is selected from then on.

Outras dicas

You need to add them to a ButtonGroup.

Try reading the control "howto":

http://docs.oracle.com/javase/tutorial/uiswing/components/button.html

It covers all this and more...

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top