Choice Components

CheckBox

To create a Checkbox use:

Checkbox(String s)  

Checkbox Example: (Run Applet)

import java.awt.event.*;
import javax.swing.*;

public class CheckboxDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel implements ItemListener
    {
        private final JCheckBox first = new JCheckBox("first");
        private final JCheckBox second = new JCheckBox("second");

        public View()
        {
            super();
            add(this.first);
            add(this.second);
            this.first.addItemListener(this);
            this.second.addItemListener(this);
        }

        @Override
        public void itemStateChanged(ItemEvent e)
        {
            showStatus("first = " + this.first.isSelected() + ". second = " + this.second.isSelected());
        }
    }
}

Radio Button

Radio buttons are held in CheckboxGroups. Only one of the Checkboxes in the group is ever set to true.

To create a CheckboxGroup (and therefore a radio button group) use:

CheckboxGroup()  

To add a Checkbox to a CheckboxGroup use:

Checkbox(String s, CheckboxGroup c, boolean state) 

Radio button Example: (Run Applet)

import java.awt.event.*;
import javax.swing.*;

public class RadioButtonDemo extends JApplet
{
    @Override
    public void init()
    {
        this.setContentPane(new View());
    }

    public class View extends JPanel implements ItemListener
    {
        private final JRadioButton first = new JRadioButton("first", false);
        private final JRadioButton second = new JRadioButton("second", true);

        public View()
        {
            super();
            //Group the radio buttons.
            ButtonGroup group = new ButtonGroup();
            group.add(this.first);
            group.add(this.second);

            add(this.first);
            add(this.second);
            this.first.addItemListener(this);
            this.second.addItemListener(this);
        }

        @Override
        public void itemStateChanged(ItemEvent e)
        {
            showStatus("first = " + this.first.isSelected() + ". second = " + this.second.isSelected());
        }
    }
}
 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>