Thursday, 14 May 2015

Choice Menus in Java

Choice menus-often called pop-up menus-are designed to allow the user to select an option from a menu and see the value chosen at all times. Figures 17.26 and 27 show how this works. The label of the Choice menu is the currently selected menu item. Choice menus can be constructed as shown in Listing 17.20.

Listing 17.20. Creating a Choice menu.
import java.awt.*;
import java.applet.Applet;


public class popup_menus extends Applet
{
    public void init()
    {
        Choice a_menu; 

        //create the new choice item
        a_menu = new Choice(); 
        //add the menu items
        a_menu.addItem("Red"); 
        a_menu.addItem("Green"); 
        a_menu.addItem("Blue"); 
        //add the menu to the applet panel
        add(a_menu);
    }

}

You can add any number of items to a Choice menu, but you can't add hierarchical menus as you can with regular menus. The creator method and other useful methods follow.
new Choice()
Creates a new Choice item.
addItem(String the_item_name)
Adds an item to the Choice menu. It can throw a NullPointerException. This is a synchronized method.
int countItems()
Returns the number of items currently in the menu.
String getItem(int menu_item_number)
Returns the text of the specified menu item (item 0 is the first item in the menu).
int getSelectIndex()
Returns the index of the currently selected item (item 0 is the first item in the menu).
String getSelectedItem()
Returns the text of currently selected menu items.
select(int menu_item)
Changes the selection to the specified item. This is a synchronized method, and it can throw IllegallArgumentException.
select(String menu_item_name)
Selects the menu item for which the name is the specified string.  
  

No comments:

Post a Comment