How do I create radio buttons in AWT?

Scott Stanchfield

AWT uses the Checkbox class for both check boxes and radio buttons.

To create a radio button, you need to create check boxes, and add them to a checkbox group. For example

package sample;

import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Test1 {
  public static void main(String[] args) {
    Frame f = new Frame();
    f.setLayout(new GridLayout(0,1));
    CheckboxGroup group = new CheckboxGroup();
    f.add(new Checkbox("One", group, true));
    f.add(new Checkbox("Two", group, false));
    f.add(new Checkbox("Three", group, false));
    f.add(new Checkbox("Four", group, false));
    f.pack();
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }});
    f.setVisible(true);
  }
}

The true and false parameters specify which radio button is initially selected. Radio buttons will be mutually exclusive within each group. You can have as many groups as you would like in your GUI.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact