5 Ways to Create an AWT Checkbox

The following example illustrates creating an AWT Checkbox using its five constructors. This tutorial will also cover all the core methods of the Checkbox class.

import java.awt.*;
import java.awt.event.*;
class AWTCheckbox extends Frame
{
Checkbox c1,c2,c3,c4,c5;
CheckboxGroup cg;

    public AWTCheckbox()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Checkbox in AWT Demo");
        setLayout(new FlowLayout());
       
        // Create a group
        // Checkboxes in a group become
        // radio buttons
        cg=new CheckboxGroup();
       
        // No label, not selected
        c1=new Checkbox();
       
        // Labeled and not selected
        c2=new Checkbox("Checkbox 2");
       
        // Labeled and selected
        c3=new Checkbox("Checkbox 3",true);
       
        // -- Radio buttons -- //
       
        // Labeled, selected and in cg group
        c4=new Checkbox("Checkbox 4",true,cg);
       
        // Same as above but parameter shift
        c5=new Checkbox("Checkbox 5",cg,true);
       
        // Set to a checkbox group
        // Now c3 becomes a radio button
        c3.setCheckboxGroup(cg);
       
        // -- Other methods -- //
       
        // Set label
        c1.setLabel("Checkbox 1");
       
        // Set state
        c2.setState(true);
       
        // Add all checkboxes
        add(c1);
        add(c2);
        add(c3);
        add(c4);
        add(c5);
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AWTCheckbox();
    }
}

In the above example, c4 and c5 are set selected but as they belong to a group and that only one checkbox in a group has to be selected, the checkbox whose state is set last will come selected in AWT, so is c5 selected. You might also want to check out using ItemListener for Checkbox.

AWTCheckbox(): Code illustrating creating AWT Checkbox is written here.

Creating an AWT Checkbox in Java
Next: Creating AWT Choice in Java
Previous: Creating AWT TextArea in Java


Posted by at on

Tags: Abstract Window Toolkit,