Java Checkbox Example Tutorial

Java Checkbox Example Tutorial

Four check boxes nameBox, boldBox, italicBox, exitBox and one label lab are created.

nameBox = new Checkbox("Monospaced");
boldBox = new Checkbox("Bold", true);

nameBox is set with a label of Monospaced and boldBox is set with Bold and a default state of true (using overloaded constructor). That is, boldBox comes with a default selected state; but no action takes place.

exitBox = new Checkbox();
exitBox.setFont(new Font("Serif", Font.BOLD, 12));

The exitBox is created using default constructor without any label and state set. They are given separately with setLabel() and setState() methods of Checkbox class. As usual, like to any other component, background, foreground and font are set.

System.out.println("exit box label: " + exitBox.getLabel());
System.out.println("exit box state: " + exitBox.getState());

The getLabel() and getState() methods of Checkbox returns the label and state existing with the check box.

Font f1 = new Font(fontName, b+i, 20);

Three temporary variables fontName, b and i are created and values are assigned as per the check boxes selected. Using the variables, a font object f1 is created and set to Label lab using setFont() method.

Event Handling

The event generated by Checkbox (known as ItemEvent) is handled by ItemListener. itemStateChanged(ItemEvent) is the only abstract method existing in ItemListener interface and is overridden in the program. All the check boxes are registered with ItemListener using addItemListener() method. The parameter "this" represents the ItemListener. Any check box selected, the itemStateChanged() method is called and code is executed.

Note: ItemListener does not have a corresponding adapter class. Why?

Leave a Reply

Your email address will not be published. Required fields are marked *