Copyright Derek O'Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.
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 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()); } } }
Copyright Derek O' Reilly, Dundalk Institute of Technology (DkIT), Dundalk, Co. Louth, Ireland.