How to Create a Radio Button in Java

A radio button group consists of a group of radio buttons with no more than one button selected at a time. In Figure 1, the buttons labeled "age under 20," "20–39," "40–59," "over 60" collectively form a radio button group. To create a radio button group, first declare the individual button objects to be of type JRadioButton. Then declare the radio button group object to be of type ButtonGroup.



For example,

JRadioButton age1, age2, age3, age4;
ButtonGroup ageButton;


Then invoke the javax.swing.ButtonGroup constructor, as follows:

ageButton = new ButtonGroup();

The individual buttons are created using the javax.swing.JRadioButton constructor, for example

age1 = new JRadioButton(''age under 20");

The individual buttons are then added to the radio button group using the
javax.swing.Button-Group.add method, as follows:

ageButton.add(age1);

No comments:

Post a Comment