go to previous page   go to home page   go to next page



Example Program

Your Ideal Weight

Usually radio buttons are placed in (1) a panel, to control how they are displayed, and (2) a button group, to control which buttons may be active simultaneously. A button group is an object, and so must be constructed. Radio buttons are then added to it. However, it does not directly correspond to any visual display.

Let us create an application that calculates a person's ideal weight (in pounds) given their gender and height (in inches). The formula for this calculation is given in the programming exercises. For now, let us look at the graphical interface. The following code shows how a button group is constructed and how radio buttons are added to it.

public class IdealWeight extends JFrame
  . . . .
  public IdealWeight()  
    genderM = new JRadioButton("Male", true );
    genderF = new JRadioButton("Female", false );
    genderGroup = new ButtonGroup();
    genderGroup.add( genderM );
    genderGroup.add( genderF );
    . . . . .

Radio buttons generate action events which require a registered action listener. Do this as with JButtons. Use setActionCommand() to assign a command string to each button. Use addActionListener() to register a listener for each button, usually the same listener for all the buttons in a group. Use getActionCommand() in the action listener to determine which button was pushed. Our example program leaves this to the programming exercises.


How many button groups are used in this GUI?