Home » Java programming language

Java AWT Choice

Java | AWT Choice: In this tutorial, we will look at one of the Java AWT components, the AWT Choice with example.
Submitted by Saranjay Kumar, on April 29, 2020

The Choice class provides a pop-up menu to the user. The user is capable of choosing one of the options from the list. The selected item appears at the top. This class is often used when there is a large number of options to choose from and not a lot of space available to display all the items on the screen.

We can program to interact with the Choice object at runtime, by implementing the ItemListener interface. The class is capable of firing the ItemEvent objects, which we can handle by assigning an ItemListener. We will discuss more event handling in later sections.

Consider the following code -

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

public class CreateChoice extends Frame {
    CreateChoice() {
        Choice c1 = new Choice();
        Choice c2 = new Choice();

        c1.add("Apple");
        c1.add("Banana");
        c1.add("Mango");

        c2.add("C++");
        c2.add("Java");
        c2.add("Ruby");
        c2.add("Javascript");
        c2.add("Python");

        System.out.println(c2.getItemCount());
        System.out.println(c2.getSelectedItem());

        c1.setBounds(50, 50, 100, 30);
        c2.setBounds(50, 100, 100, 30);

        setLayout(null);
        setVisible(true);
        setSize(300, 300);

        add(c1);
        add(c2);
    }


    public static void main(String[] args) {
        CreateChoice ob = new CreateChoice();
    }
}

Output

Java AWT Choice

Java AWT Choice

As can be seen from the output, we obtain two pop up menus, each providing us with a list, with items to choose from. Initially, we have created two empty Choice objects, c1 and c2. The add() method lets us add String objects to c1 and c2.

String objects are displayed in the list in the same order as added. The Choice class maintains an index value, using which String objects are added. This means that we can access any item on such a list directly from its index.

Whatever item the user clicks on, gets selected and is displayed at the top, as can be seen – Apple and C++ are displayed in the two Choice objects.

Often we require to check the total number of items in a Choice object. For this, we have the getItemCount() method. It returns an integer value, representing the total count of the items. As printed on the screen, there are 5 objects in c2.

    int getItemCount()

We can also retrieve which item is presently selected by the user, using the getSelectedItem() method. It returns a String value, of the object that is selected by the user.

    String getSelectedItem()


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.