Thursday 14 May 2015

Scrolling Lists in Java

Scrolling lists display multiple lines of text, and each line corresponds to a selection item. Scroll bars are displayed if the text is larger than the available space. The user can select one or more of the lines. Your program can read the user's selections. Lists generate three event types:
  • ACTION_EVENT: When a list item is double-clicked. The argument is the name of the list item.
  • LIST_SELECT: When a list item is selected. The argument is the name of the list item selected.
  • LIST_DESELECT: When a list item is deselected. The argument is the name of the item deselected.

The applet shown in Listing 17.21 shows how to create single- and multiple-choice scrolling lists. Figure 17.28 shows the resulting interface elements. Note that the scrollbar for the left list is disabled because all the items in the list are visible.

Listing 17.21. Creating single- and multiple-choice scrolling lists.
import java.awt.*;
import java.applet.Applet;


public class list extends Applet
{
    public void init()
    {
        List mult_choice, single_choice;

        //define a scrolling list that shows 6 elements at a time and that
        //allows the selection of multiple items at the same time
        mult_choice = new List(6,true);
        single_choice = new List();
        //define the list entries
        mult_choice.addItem("Red"); 
        mult_choice.addItem("Green"); 
        mult_choice.addItem("Blue"); 
        mult_choice.addItem("Yellow"); 
        mult_choice.addItem("Black"); 
        mult_choice.addItem("Azure"); 
        single_choice.addItem("Chicago"); 
        single_choice.addItem("Detroit"); 
        single_choice.addItem("Los Angeles");
        single_choice.addItem("Atlanta"); 
        single_choice.addItem("Washington"); 
        single_choice.addItem("Lincoln"); 
        single_choice.addItem("LaGrange"); 
        //add the lists to the applet panel
        add(mult_choice); 
        add(single_choice); 

    }
}

The key methods you'll most commonly use with lists follow.
addItem(String item_label)
Adds the specified item to the end of the current list of items in the list. This is a synchronized method.
addItem(String item_label, int location)
Adds the specified item to the list at the specified location. This is a synchronized method. Remember that the first item in the list is numbered 0. For example, addItem("a test", 3) puts "a test" into the fourth position in the list and slides the previous fourth entry and all entries after it down one.
int clear()
Removes all the entries in the list. This is a synchronized method.
int countItems()
Returns the number of items currently in the list.
delItem(int location)
Deletes the list item at the specified location. This is a synchronized method.
delItems(int first, int last)
Deletes all the items between the first and last location, inclusive. This is a synchronized method. For example, delItems(1,3)-note the s at the end of Item-deletes the second, third, and fourth entries in the list; remember that the first location is 0.
deselect(int location)
Deselects the item at the specified location. This is a synchronized method.
String getItem(int location)
Returns the label of the list item at the specified location.
int getRows()
Returns the number of rows currently visible to the user.
int getSelectedIndex()
Throws an ArrayIndexOutofBoundsException if it's invoked on a list where more than one item is selected. The method returns -1 if no items are selected. This is a synchronized method.
int[] getSelectedIndexes()
Returns an array of the locations of the selected items. This is a synchronized method. It works with a single selection and with single-selection lists. It returns -1 if no items are selected.
String getSelectedItem()
Returns the location of the currently selected item. This is a synchronized method. A runtime Exception is thrown if this method is called on a multiple-selection list. For that reason, and the fact that getSelectedItems will work with a single item, it's best to avoid this method. If no item is selected, it returns NULL.
String[] getSelectedItems()
Returns an array of Strings containing the names of the currently selected list items. This is a synchronized method. It returns an empty array if no items are selected. In that case, trying to access the 0th array item, as in
String [] picked = list.getSelectedItems() 
String x = picked[0];
raises an ArrayIndexOutofBoundsException.
makeVisible(int location)
Forces the item at the specified location to be visible. This is a synchronized method. It comes in handy because not all choices are visible to the user if the number of visible rows is less than the number of list items. The specified location is moved to the top of the visible area.
replaceItem(String new_label, int location)
Changes the name of the label specified by the value of location. This is a synchronized method.
select(int location)
Selects the specified item. This is a synchronized method.
Because the List class has such an extensive set of methods for manipulating the list's contents, it's a good choice for displaying information that is going to change often. It would be a good choice for showing recently visited pages-with event support to rapidly return to those pages-or the list of shopping items the user wants to purchase.

The TextComponent Class-Invisible but Useful

This class is abstract, but it's extended by both TextFields and TextAreas. All the methods covered here are available in both those GUI elements. TextComponent provides the basic tools for finding out what text is in a Text item (getText), setting the text in an item (setText), and selecting pieces of text (setSelect). When using TextFields or TextAreas, you won't have to worry about managing the cursor location, the insertion point (the vertical cursor that tells the user where newly typed text will be inserted), or the marking of the selected text. All these functions are done for you by the AWT. The most useful TextComponent methods follow.
String getSelectedText()
Returns the text currently selected in the text item. The text may have been selected by the user or through the setSelection method.
int getSelectionEnd()
Returns the index of the last character in the selection +1. Suppose that you pick a single character such as index 3; this method returns 4. If no characters are selected, this method returns the location of the insertion point. In that case, this method and getSelectionStart return the same value.
int getSelectionStart()
Returns the index of the first character in the current selection or the location of the insertion point if nothing is selected.
String getText()
Returns all the text in the text item.
select(int start, int stop)
Selects the text specified by input arguments. As with getSelectionEnd, the end value should be the index of the last character you want to select +1. If start and stop are the same value, the insertion point is placed immediately before the character with that index.
selectAll
Selects all the text in the text item.
setEditable(boolean state)
Enables you to toggle between whether or not a text item is editable by the user.
setText(String new_text)
Enables you to set the text in the text item. This replaces all the text in the item. If you want to insert or append text, you need to use getText, modify the string, and then use setText to put the modified string back in the text item. Note that TextArea has insert and append methods.
The applet in Listing 17.22 shows you how the various methods work. You'll see more about the unique characteristics of TextFields and TextAreas in the next two sections.
Listing 17.22. TextFields and TextAreas in action.
import java.awt.*;
import java.applet.Applet;


public class text_stuff extends Applet
{
    TextArea text_space;
    TextArea selection;
    Button show_selection, make_selection; 
    TextField start, stop;

    public void init()
    {
        int i;
        String sample_text; 

        //This string could have included \n to force returns
        sample_text = "This is a very long piece of text which is" +
        " designed to show how " +
        "a text area can hold a lot of text without you having to do a lot of" +
              "work." +
        "In general text areas are good for holding large chunks of text or for" +
         "getting " +
        "long answers back from the user.  TextAreas have lots of methods for " +
        "manipulating the their contents and for controlling how the text is " +
        "scrolled"; 
        //define the TextArea 
        text_space = new TextArea(sample_text,8,50);
        //define the report TextArea
        selection = new TextArea("",10,50);
        //create the button to show the selection values
        show_selection = new Button("Selection Report");
        //create the text field to input the start of the selection
        start = new TextField(2); 
        //create the text field to input the end of the selection
        stop = new TextField(2); 
        //make the labels for the two input fields
        Label l_start = new Label("Start of selection");
        Label l_stop = new Label("End of selection");
        //define the button to make the selection
        make_selection = new Button("Make selection");
        //add everything to the applet's panel
        add(text_space); 
        add(show_selection); 
        add(selection); 
        add(l_start); 
        add(start);
        add(l_stop);
        add(stop);
        add(make_selection); 
    }

    //handle mouse clicks on the two buttons 
    public boolean action (Event e, Object o) {
        int start_location,stop_location; 
        String report, temp;

        if (e.target instanceof Button) {
            //check the button label to decide which button was clicked
            if (((String)o).equals("Make selection")) {
                //read the text from the text field to 
                //get the start of the selection
                temp = start.getText();
                //convert the text to an integer
                start_location = Integer.parseInt(temp);
                //get the text from the text field to 
                //define the end of the selection
                temp = stop.getText();
                //convert the text to an integer
                stop_location = Integer.parseInt(temp);
                //set the selection to the interval defined by 
                //the values in the text fields
                text_space.select(start_location, 
                                          stop_location);

            } else {
                report = "Selection Start = ";
                //get the start of the current selection
                report = report + text_space.getSelectionStart() + "\n";
                //get the end of the current selection
                report = report + "Selection End = ";
                report = report + text_space.getSelectionEnd() + "\n";
                //get the selected text
                report = report + "Selected Text is: ";
                report = report + text_space.getSelectedText() + "\n";
                //put the report in the text area
                selection.setText(report); 
            } 
        }
        return true;
    }
}

 
  

No comments:

Post a Comment