Chapter 20

Choice Menu, Text Area, and Scrolling List Controls


CONTENTS

If your applet must handle only a couple of user commands, it's an easy matter to include button controls or checkbox groups in order to enable the user to select those commands. However, often, an applet's command set is sophisticated enough to warrant complete menus. Java features choice menus for just this eventuality. Java also features a scrolling list control, not unlike Windows' list box control, that enables the user to select items from a list. Finally, the text area control enables you to display paragraphs of text within your applet. You'll learn about all these controls in this chapter.

Choice Menus

Choice menus are very similar to the drop-down lists. When the user selects the menu, a list of commands appears from which the user can choose. After the user makes a choice, the menu disappears.

To create a choice menu, you must first create an instance of the Choice class, like this:


Choice menu = new Choice();

As you can see, the Choice class's constructor accepts no arguments.

After you have created the Choice object, you can add items to the menu by calling the object's addItem() method:


menu.addItem(str);

Here, str is the text that will appear as the command in the menu. You can call addItem() as often as you need to build a complete menu. When you have the complete menu created, you add it to the applet by calling the add() method.

Example: Creating a Choice Menu

Creating a menu is a fairly straightforward process. For example, to create a choice menu that enables the user to select between three font styles, you might use the code shown in Listing 20.1.


Listing 20.1  LST20_1.TXT: Creating a Choice Menu.

Choice menu = new Choice();

menu.addItem("Plain");

menu.addItem("Bold");

menu.addItem("Italic");

add(menu);


When the user runs the applet containing this menu, a menu like that shown in Figure 20.1 appears. To display the menu, the user clicks on the arrow to the right of the text box displaying the current choice, and the menu appears, as shown in Figure 20.2. To select a choice, the user merely clicks an entry in the menu.

Figure 20.1 : Java displays a choice menu as a text box with an arrow.

Figure 20.2 : Clicking the arrow displays the menu.

Choice Menu Methods

As you've no doubt guessed, the Choice class features a number of public methods that enable you to manipulate choice menus in various ways. Using these methods, you can do everything from determining the number of command entries in a menu to adding items to the menu. Table 20.1 lists the most commonly used methods and their descriptions.

Table 20.1  Methods of the Choice Class.

MethodDescription
int countItems()Returns the number of command items in the menu.
String getItem(int index)Returns the command text for a given item.
void addItem(String item)Adds an item to the menu.
String getSelectedItem()Returns a string representing the selected item.
int getSelectedIndex()Returns the index of the selected item.
void select(int index)Selects the item at the given position.
void select(String str)Selects the item with the given text string.

Example: Responding to Menu Events in an Applet

A menu isn't much good unless you can determine which item the user selected so that the applet can carry out the user's command. As with most controls, when the user makes a selection from a choice menu, Java generates an event that you can capture in the action() method. In the case of a choice menu, action()'s first parameter is the menu instance, and the second parameter is the text of the selected menu item. By comparing the text to the items you added to the menu, you can determine which menu item the user chose.

The ChoiceApplet applet, whose source code is shown in Listing 20.2, demonstrates creating and responding to choice menus in an applet. Listing 20.3 is the applet's HTML document. When you run the applet under Appletviewer, you see the window shown in Figure 20.3. The text in the window is displayed using the currently selected color in the choice menu. To change the text color, just select a new menu item.

Figure 20.3 : ChoiceApplet displays text in the color selected from its choice menu.


Listing 20.2  ChoiceApplet.java: Using Menus in an Applet.

import java.awt.*;

import java.applet.*;



public class ChoiceApplet extends Applet

{

    Choice menu;

    Color color;



    public void init()

    {

        Choice menu = new Choice();



        menu.addItem("Black");

        menu.addItem("Red");

        menu.addItem("Green");

        menu.addItem("Blue");



        add(menu);



        color = Color.black;

    }



    public void paint(Graphics g)

    {

        Font font = new Font("TimesRoman", Font.BOLD, 24);

        int height = font.getSize();

        g.setFont(font);



        g.setColor(color);



        g.drawString("This text is drawn in", 32, 75);

        g.drawString("the color selected from", 32, 75+height);

        g.drawString("the above choice menu.", 32, 75+2*height);

    }



    public boolean action(Event evt, Object arg)

    {

        if (evt.target instanceof Choice)

            HandleMenu(arg);



        return true;

    }



    protected void HandleMenu(Object item)

    {

        if (item == "Black")

            color = Color.black;

        else if (item == "Red")

            color = Color.red;

        else if (item == "Green")

            color = Color.green;

        else

            color = Color.blue;



        repaint();

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the ChoiceApplet class from Java's Applet class.
Declare menu and color objects.
Override the init() method.
Create the menu object.
Add commands to the menu object.
Add the menu to the applet.
Initialize the starting color for the text.
Override the paint() method.
Create and set the display font.
Set the selected color.
Display text in the selected color.
Override the action() method.
If the menu caused the event, call the HandleMenu() method.
Tell Java that the event was handled okay.
Declare the HandleMenu() method.
Set the color field based on the menu selection.
Tell Java to repaint the applet's display area.

Listing 20.3  CHOICEAPPLET.htmL: ChoiceApplet's HTML Document.

<title>Applet Test Page</title>

<h1>Applet Test Page</h1>

<applet

    code="ChoiceApplet.class"

    width=300

    height=150

    name="ChoiceApplet">

</applet>


Scrolling Lists

Whereas choice menus usually display a set of commands or options, scrolling lists are best used to display a list of items from which the user can choose. For example, you might use a scrolling list to enable the user to choose a state when filling out an address form. The scrolling list in this case would contain all 50 states. The user would only need to double-click on his or her state in order to complete that section of the form. Scrolling lists not only make it easy for users to enter information, but also ensure that the user makes a choice from a valid set of responses.

To create a scrolling list, you first call the List class's constructor, like this:


List list = new List(num, false);

The constructor's two arguments are the number of visible lines in the list and a boolean value indicating whether the list will support multiple selections. The list created in the preceding will not allow the user to select more than one item simultaneously.

When you have the list object created, you can add items to the list. You do this by calling the List object's addItem() method:


list.addItem(str);

Here, str is the text string for the item to add to the list.

NOTE
You can add as many items as you like to a list. You are not limited to the number of items given as the List constructor's first argument. That value specifies only the size of the list box; that is, the value determines how many items are visible on the screen at one time.

Example: Creating a Single-Selection List

Suppose that you need to create a list that contains musical artists from which the user must select only one. First, you create the list object, after which you add the names of the artists you want to include. Finally, you add the list to the applet. Listing 20.4 shows the Java code that performs these tasks. Figure 20.4 shows the resultant list box.

Figure 20.4 : In this list, only one item can be selected at a time.


Listing 20.4  LST20_4.TXT: Creating a Single-Selection List Box.

List list = new List(10, false);

list.addItem("Pearl Jam");

list.addItem("Dream Theater");

list.addItem("Joe Satriani");

list.addItem("Oasis");

list.addItem("Alanis Morissette");

list.addItem("Soul Asylum");

list.addItem("The Rembrandts");

list.addItem("Smashing Pumpkins");

list.addItem("Joan Osborne");

list.addItem("Bjork");

add(list);


Because the List constructor's first argument is 10 and there are only 10 items in the list, all of the items are visible on the screen. Moreover, because the List constructor's second parameter is false, in the list created by Listing 20.4, the user can select only a single artist at a time.

Example: Creating a Multiple-Selection List

When you display a list of musical artists such as that created by Listing 20.4, you may want the user to select more than one. In this case, you can create a multiple-selection list, just by changing the List constructor's second argument to true, like this:


List list = new List(10, true);

As Figure 20.5 shows, the new list enables the user to select as many artists as he or she likes.

Figure 20.5 : Now the user can select more than one artist at a time.

Example: Creating a Scrolling List

You may have noticed that in this chapter's title, the list controls are called "scrolling lists." So far, though, none of your lists have scrolled. In fact, they haven't even had scroll bars. Whenever the size of the list box (given as the constructor's first argument) is greater than or equal to the number of items in the list, the list doesn't need to scroll, so no scroll bar appears. However, as soon as the number of items exceeds the size of the list box, Java enables scrolling.

As an example, suppose that you were to change the first line of Listing 20.4 to this:


List list = new List(5, false);

Now, you have a list that can display five items at a time. However, there are 10 items in your list, which means that, in order for the user to be able to see all then items, the list must scroll. Figure 20.6 shows the resultant scrolling list.

Figure 20.6 : The user must scroll this list to see all the items.

Methods of the List Class

Because there's so much you can do with a scrolling list control, the List class has a large set of public methods that you can call to manipulate a list. The most useful of these methods are listed in Table 20.2. Although there are a lot of methods to learn in the table, the most important are addItem(), getSelectedIndex(), getSelectedIndexes(), getSelectedItem(), and getSelectedItems(). Using these five methods, you can create a basic scrolling list and enable the user to make selections from it. In the next section, in fact, you'll see how to determine which item the user selected.

Table 20.2  Most Useful Methods of the List Class.

MethodDescription
void addItem(String item)Adds an item to the end of the list.
void addItem(String item, int index) Adds an item to a specific position in the list.
boolean allowsMultipleSelections() Returns a boolean value indicating whether the list supports multiple selection.
void clear()Clears all items from the list.
int countItems()Returns the number of items in the list.
void delItem(int position)Deletes the item at the given position from the list.
void delItems(int start, int end) Deletes a group of items from the list.
void deselect(int index)Deselects the item at the given index.
String getItem(int index)Returns the item at the given index.
int getRows()Returns the size of the list box.
int getSelectedIndex()Gets the index of the selected item.
int[] getSelectedIndexes() Gets the indexes of a multiple selection.
String getSelectedItem()Returns the selected item in a list.
String[] getSelectedItems()Returns all the items in a multiple selection.
int getVisibleIndex()Returns the index of the last item that was made visible.
boolean isSelected(int index) Returns a boolean value indicating whether the item at the given index is selected.
void makeVisible(int index)Ensures that the item at the given index is visible.
void replaceItem(StringReplaces the item at the given newValue, int index)index with a new item.
void select(int index)Selects the item at the given index.
void setMultipleSelections(boolean v) Toggles the multiple-selection mode.

Example: Using a Scrolling List in an Applet

By now, you've gotten used to working with the list of musical artists that I've used in the previous few examples. In this example, you put that list to the test by not only creating and displaying the list in an applet, but also by displaying the user's selection. Listing 20.5 is the source code for the ListApplet applet.


Listing 20.5  ListApplet.java: An Applet with a Scrolling List.

import java.awt.*;

import java.applet.*;



public class ListApplet extends Applet

{

    List list;



    public void init()

    {

        list = new List(5, false);



        list.addItem("Pearl Jam");

        list.addItem("Dream Theater");

        list.addItem("Joe Satriani");

        list.addItem("Oasis");

        list.addItem("Alanis Morissette");

        list.addItem("Soul Asylum");

        list.addItem("The Rembrandts");

        list.addItem("Smashing Pumpkins");

        list.addItem("Joan Osborne");

        list.addItem("Bjork");



        add(list);

        resize(300, 150);

    }



    public void paint(Graphics g)

    {

        g.drawString("CHOSEN ITEM:", 100, 110);

        String s = list.getSelectedItem();



        if (s == null)

            s = "None";



        g.drawString(s, 100, 130);

    }



    public boolean action(Event evt, Object arg)

    {

        repaint();

        return true;

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the ListApplet class from Java's Applet class.
Declare the list object.
Override the init() method.
Create the list object.
Add items to the list object.
Add the list to the applet.
Set the applet's size.
Override the paint() method.
Draw a label in the applet's display.
Get the selected item from the list box.
If there is no item selected, set the string to "None."
Display the selected item.
Override the action() method.
Force the applet to repaint its display.
Tell Java that the event was handled okay.

When you run ListApplet with Appletviewer, you see the window shown in Figure 20.7. When you double-click an item in the list, Java calls the applet's action() method in which the applet calls the repaint() method. This forces Java to call the paint() method, where the applet retrieves the selected item and displays it.

Figure 20.7 : The scrolling list in this applet lets you choose a single musical artist.

Notice the call to resize() in the init() method. The resize() method enables you to set the applet to any size you wish. This size overrides any size setting that's included in the HTML document that ran the applet.

The TextArea Control

Throughout this book, you've been using the TextField control to retrieve information from the user. In most cases, the TextField control works great, but it does have some limitations, the most serious being the fact that it can display only one line of text at a time. There may be situations where you'd like to display one or more paragraphs of text in your applet, in a control that enables the user to edit existing text, as well as enter his or her own text. This is where the TextArea control is useful. The TextArea control is a text box that acts like a simple word processor. When you display a text box, the user can type and edit multiple lines of text.

To create a TextArea control, you call the class's constructor, like this:


TextArea textArea = new TextArea(str, rows, cols);

This constructor's three arguments are the string to display in the control, the number of rows in the control, and the number of columns. As with the other controls, after you create the TextField object, you add it to the applet by using the add() method.

Example: Creating a TextArea Control

As an example, suppose that you need to create a TextArea control that'll start off displaying eight lines of text. Listing 20.6 is an applet, called TextAreaApplet, that creates a TextArea control that displays eight lines of text. Figure 20.8 shows what the applet looks like running under Appletviewer. When you run the applet, click on the TextArea control's box and try editing the text in the window. As you'll discover, you not only can edit the existing text, but also add new text.

Figure 20.8 : TextAreaApplet applet run-ning under Appletviewer.


Listing 20.6  TEXTAREAAPPLET.JAVA: The TextAreaApplet Applet.

import java.awt.*;

import java.applet.*;



public class TextAreaApplet extends Applet

{

    TextArea textArea;



    public void init()

    {

        String s = "This is an example of a\n";

        s += "textarea control, which is not\n";

        s += "unlike a textfield control.\n";

        s += "The big difference is that a\n";

        s += "textarea control can hold many\n";

        s += "lines of text, whereas a\n";

        s += "textfield control deals with\n";

        s += "only one line of text at a time.\n";



        textArea = new TextArea(s, 9, 30);

        add(textArea);



        resize(300, 180);

    }

}


Tell Java that the applet uses the classes in the awt package.
Tell Java that the applet uses the classes in the applet package.
Derive the TextAreaApplet class from Java's Applet class.
Declare the TextArea object.
Override the init() method.
Create the string to display in the control.
Create the TextArea object.
Add the control to the applet.
Set the applet's size.

TIP
If you look at how the TextArea control's display string is created in TextAreaApplet, you'll see that you can store multiple lines of text into a single String object. You do this by placing the newline character (\n) at the end of each line that you add to the string.

When you run TextAreaApplet, notice how all the text fits within the text box. Because the text is fully displayed, the control's scroll bars are inactive. However, if you were to edit the text such that you added more lines than the control can display, or made a line longer that the control can display, the control's scroll bars become active. Figure 20.9 shows TextAreaApplet after the user has added text that forces the scroll bars to become active. You can use the scroll bars to view the portions of the text that are offscreen.

Figure 20.9 : When the text contained in the control cannot be fully displayed, a TextArea control activates its scroll bars.

Methods of the TextArea Class

To enable you to easily manipulate the text, the TextArea class features a number of public methods. You can use these methods to modify the text in the control or to obtain information about the control. Table 20.3 shows the most useful methods and what they do.

Table 20.3  Useful Methods of the TextArea Class.

MethodDescription
void appendText(String str)Appends text to the control.
int getColumns()Returns the number of columns in the control.
int getRows()Returns the number of rows in the `control.
void insertText(String str,Inserts text at the given position.int pos)
void replaceText(String str,Replaces text specified by the int start, int end)starting and ending points.

Summary

Choice menus are a powerful control that enable you to include a pop-up menu of commands for the user of your applet. By using such a menu, the user can more easily control the applet, as well as set options, without the controls' taking up a lot of screen space. Scrolling lists are a valuable tool for ensuring that the user always enters a response from a valid set of responses. You can even set up a list to accept multiple selections. Finally, the TextArea control provides a simple text editor that you can easily add to your applets.

Review Questions

  1. How many arguments are accepted by the Choice class's constructor?
  2. How do you add items to a choice menu?
  3. What are the two arguments needed by the List class's constructor?
  4. How do you add items to a scrolling list?
  5. When would you use a TextArea control in place of a TextField control?
  6. How can you determine which menu command the user selected?
  7. How do you create a multiple-selection scrolling list?
  8. How do you retrieve the selected item from a single-selection scrolling list?
  9. How do you create a single string containing multiple lines of text?
  10. How do you retrieve multiple selections from a scrolling list?
  11. Can you delete items from a scrolling list?

Review Exercises

  1. Write an applet that has a menu containing the commands On and Off.
  2. Write an applet that displays a single-selection scrolling list containing the titles of five movies.
  3. Write an applet that displays a TextArea control. The control should display five lines of text at startup.
  4. Write an applet that changes the size of the applet based on five selections in a choice menu.
  5. Revise the applet from exercise 3 such that the user uses a single-selection list to select the applet's size.
  6. Write an applet called TextTransferApplet that includes a list box and a TextArea control. The list box should contain 10 words. When the user clicks a word, the word should appear in the TextArea control on a new line. Figure 20.10 shows what the completed applet should look like, and Figure 20.11 shows the applet after the user has transferred several words to the TextArea control. You can find the solution for this problem in the CHAP20 folder of this book's CD-ROM.

Figure 20.10 : TextTransferApplet should look like this.

Figure 20.11 : Here's the applet after the user has transferred a few words to the text area.