Radio Buttons require two objects. They need all a radio button for each of the options that you require and they need a button group to group all of the radio buttons. The button group is to restrict the user to one selection in the group - that is how radio buttons work, the user gets only one selection of the list.
| Declare button group to hold all of the buttons | ButtonGroup bg1 = new ButtonGroup (); |
| Declare string constants for each button's action command and label - this is not necessary, you can just type it out wherever the constants are used. | protected final static String Pascal = "Blaise Pascal"; |
| Declare a radio button for each option. | JRadioButton pas = new JRadioButton (); |
| Set up the options for the radio button, add action listeners. | pas.setText (Pascal); pas.setActionCommand (Pascal); pas.addActionListener (this); |
| For ONE radio button in the group, set it to default to turn on. | pas.setSelected (true); |
| Add the radio button to the button group | bg1.add (pas); |
| Add the radio button to the screen. You do NOT add the button group. | add (pas); |
Panels can be used to make the radio buttons arrange themselves more nicely.
import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*;
public class radiobuttons extends Applet implements ActionListener
{
//constants for action commands
protected final static String Pascal = "Blaise Pascal";
protected final static String Wiles = "Andrew Wiles";
protected final static String Turing = "Alan Turing";
protected final static String Brooks = "Fred Brooks";
ButtonGroup bg1 = new ButtonGroup (); JPanel p1 = new JPanel (new FlowLayout ());
public void init ()
{
JRadioButton pas = new JRadioButton ();
pas.setText (Pascal);
pas.setActionCommand (Pascal);
pas.addActionListener (this);
pas.setSelected (true);
bg1.add (pas);
JRadioButton wil = new JRadioButton (); wil.setText (Wiles); wil.setActionCommand (Wiles); wil.addActionListener (this); bg1.add (wil);
JRadioButton tur = new JRadioButton (); tur.setText (Turing); tur.setActionCommand (Turing); tur.addActionListener (this); bg1.add (tur);
JRadioButton bro = new JRadioButton (); bro.setText (Brooks); bro.setActionCommand (Brooks); bro.addActionListener (this); bg1.add (bro);
add (pas); add (wil); add (tur); add (bro); }
/**
Displays the name and clears the text field
@param e.getActionCommand contains nothing or clearArea
*/
public void actionPerformed (ActionEvent e)
{
String command = e.getActionCommand ();
showStatus (command + " was selected");
if (Brooks.equals (command))
{
showStatus ("A Turing Award Winner was selected");
}
} }