ButtonGroup Class

Package: javax.swing

The ButtonGroup class creates a group in which you can add radio buttons. Of course, only one radio button in a button group can be selected at any time. Thus, selecting a radio button in a button group automatically deselects any other buttons in the group.

Constructor

Constructor

Description

ButtonGroup()

Creates an empty button group

Method

Method

Description

void add(Abstract Button button)

Adds a button to the group

tip.eps You’ll usually add only radio buttons to a button group, but you can add regular buttons or check boxes, too.

Before you create a button group, you should create the buttons you will add to it. Here’s an example that creates three radio buttons named small, medium, and large:

JRadioButton small, medium, large;

Now that you have buttons, you can create a button group by calling the ButtonGroup class constructor. Then, you can add the buttons to the button group by calling the add method. For example:

ButtonGroup group1 = new ButtonGroup();

group1.add(small);

group1.add(medium);

group1.add(large);

CrossRef.eps Button groups have nothing to do with the visual appearance of the buttons on the screen. Instead, button groups simply provide a logical grouping for the buttons. To visually group the buttons together, add them to a panel. For more information, see JPanel Class.

Where button groups really come in handy is when you have more than one set of radio buttons in a form. Suppose that you want to create a dialog box that lets a user order pizza, choosing the size of the pizza and the style of crust. In addition to choosing the size of the pizza (small, medium, or large), the user can choose the style of crust: thin or thick. In that case, you use five radio buttons, in two button groups. The constructor code that creates the radio buttons might look something like this:

ButtonGroup size = new ButtonGroup();

ButtonGroup crust = new ButtonGroup();

small = new JRadioButton(“Small”);

medium = new JRadioButton(“Medium”);

large = new JRadioButton(“Large”);

size.add(small);

size.add(medium);

size.add(large);

thin = new JRadioButton(“Thin Crust”);

thick = new JRadioButton(“Thick Crust”);

crust.add(thin);

crust.add(thick);

tip.eps Strictly speaking, you don’t have to create a button group if all the radio buttons in the frame are in the same group. In that case, Swing creates a default group and adds all the radio buttons to it. Because it requires only a few extra lines of code, however, I suggest that you always create a button group — even when you have only one group of radio buttons.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset