What is Java Choice with Example?

What is Java Choice with Example?

Java comes with many GUI components placed in java.awt package. One component is Java Choice (in other GUI technologies, it is known as combo box).

1. What is Java Choice component?
2. When to use Choice?

Choice is replacement to radio buttons. When radio buttons are many to display, they flock all the frame. As an alternative, the java.awt package comes with Choice. That is, Choice is meant for single selection only.

3. How Choice component looks?

Choice gives a dropdown list of items from which user can select only one. When selected, the dropdown list disappears displaying the selected item.

4. What event Choice generates and the listener that handles?

Choice generates ItemEvent and is handled by ItemListener.

5. How to know which item user selected in Choice?

Choice class comes with two methods – getSelectedItem() returning the item selected by the user as a string and getSelectedIndex() returning the item index number selected by the user as an integer value. The first item added to Choice gets 0 index number by default.

Following is a simple program on Java Choice component (a big program we see later) to get the concept. User selection is displayed at DOS prompt for simplicity.

Java Choice
Output screenshot on Java Choice Example

Generally in menu cards, the serial number starts with 1 and not with 0. For this reason, num+1 is given.

A big program with full explanation with screen shot is given at Java AWT Choice – Replacement to Radio Buttons

Leave a Reply

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