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

Answer:

Yes.


Example Program

Your Ideal Weight

Usually radio buttons are added to a panel that affects how they are displayed, and added to a button group that controls which button is active. 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()  
  { 
    // Construct Radio Buttons
    genderM = new JRadioButton("Male", true );
    genderF = new JRadioButton("Female", false );
  
    // Construct a ButtonGroup and add buttons to it
    genderGroup = new ButtonGroup();
    genderGroup.add( genderM );
    genderGroup.add( genderF );
    . . . . .
  } 
}  

Radio buttons generate action events and require a registered action listener. This is the same as with JButtons.

  1. Use setActionCommand() to assign a command string to each button.
  2. Use addActionListener() to register a listener for each button, usually the same listener for all the buttons in a group.
  3. Use getActionCommand() in the action listener to determine which button was pushed.

Our example program leaves this to the programming exercises.


QUESTION 3:

How many button groups are used in this GUI? (Look at the picture.)