Java Made Simple: Create Checkbox Example

Java Made Simple: Create Checkbox Example


Checkbox Example tutorial is given in Question/Answer format for easy understanding.

1. What is Checkbox?

Checkbox is one of the GUI components Java supports.

2. When Checkbox is preferred by the Programmer?

Checkbox is used when the user has got only two options to choose in between like Yes or No, Want or Dont want.

3. How to create a Checkbox component?

Checkbox cb1 = new Checkbox("Hero Honda"); OR
Checkbox cb2 = new Checkbox("Hero Honda", true);

cb1 displays a checkbox with label Hero Honda; here, the checkbox is NOT SELECTED by default.
cb2 displays a checkbox with label Hero Honda; here, the checkbox is SELECTED by default which user can change.

4. How to know which checkbox is selected by user?

The getState() method of Checkbox class returns true if the user selected the checkbox else false.

boolean b = cb1.getState();
System.out.println(b);

b prints true if user selects (or checks) the checkbox cb1, else b prints false.

5. Which event is generated by Checkbox?

When user selects a checkbox, the checkbox generates an event known as ItemEvent (from java.awt.event package).

6. What is the listener interface that handles the ItemEvent successfully?

ItemListener (from java.awt.event package) is capable to handle the event ItemEvent.

7. Can we use checkboxes in applets also?

Yes; infact you can use any GUI component in applets (apart in frame) also. But menus cannot be done in applets.

To get the concept, a simple program is given explaining how to use checkboxes. A big program, we see later.

Checkbox Example: Just two checkboxes are created and added to frame with labels Hero Honda and Activa. For simplicity, user selection is displayed at DOS prompt.


Checkbox Example
Output screenshot with different options selected. Observe, the last option and the screen.

A big and different program with full explanation and screenshot is available at Java AWT Checkbox – Toggle Button

Leave a Reply

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