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 ?

有帮助吗?

解决方案

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.

其他提示

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...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top