Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

178 HOUR 13:Building a Simple User Interface


You can present a JCheckBoxsinglyor as part of a group. In a group of
check boxes, only one can be checked at a time. To make a JCheckBox
object part of a group, you have to create a ButtonGroupobject. Consider
the following:
JCheckBox frogLegs = new JCheckBox(“Frog Leg Grande”, true);
JCheckBox fishTacos = new JCheckBox(“Fish Taco Platter”, false);
JCheckBox emuNuggets = new JCheckBox(“Emu Nuggets”, false);
FlowLayout flo = new FlowLayout();
ButtonGroup meals = new ButtonGroup();
meals.add(frogLegs);
meals.add(fishTacos);
meals.add(emuNuggets);
setLayout(flo);
add(jumboSize);
add(frogLegs);
add(fishTacos);
add(emuNuggets);

This creates three check boxes that are all grouped under the ButtonGroup
object called meals. The Frog Leg Grande box is checked initially, but if the
user checked one of the other meal boxes, the check next to Frog Leg
Grande would disappear automatically. Figure 13.4 shows the different
check boxes from this section.

Combo Boxes
AJComboBox component is a pop-up list of choices that also can be set up
to receive text input. When both options are enabled, you can selectan
item with your mouse or use the keyboard to enter text instead. The
combo box serves a similar purpose to a group of checkboxes, except that
only one of the choices is visible unless the pop-up list is being displayed.
To create a JComboBoxobject, you have to add each of the choices after cre-
ating the object, as in the following example:
JComboBox profession = new JComboBox();
FlowLayout flo = new FlowLayout();
profession.addItem(“Butcher”);
profession.addItem(“Baker”);
profession.addItem(“Candlestick maker”);
profession.addItem(“Fletcher”);
profession.addItem(“Fighter”);
profession.addItem(“Technical writer”);
setLayout(flo);
add(profession);

FIGURE 13.4
Displaying check box components.

Free download pdf