These present scrolling lists (list boxes) where the user can select an item (single-selectable lists) or several items (multi-selectable lists). Like Choice menus, you first create an empty one, then add items to it via addItem (Java 1.0) or add (Java 1.1), as below:
List list = new List();
list.addItem("...");
list.addItem("...");
...
add(list);
This creates a listbox with the specified number of visible rows. The number of rows specified affects the height of the List box, not the maximum number of possible entries. If more are added, a scrollbar is automatically created. The second argument determines if the List is multiselectable. As with Choice menus, an empty List is created, then items are added to it with addItem or add. The preferred width is set to a platform-dependent value, and is typically
not
directly related to the width of the widest entry. Of course, you can always resize it explicitly if your layout manager permits it.
This creates a single-selectable list box with a platform-dependent number of rows and a platform-dependent width.
This creates a single-selectable list box with the specified number of rows and a platform-dependent width.
Listing 13.19 creates two lists. The first allows a single selection only, while the second permits multiple selections. Figures 13-18, 13-19, and 13-20 show the results on Windows 95, MacOS, and Solaris.
Listing 13.19
|
|---|
import java.awt.*;
public class Lists extends QuittableFrame {
public static void main(String[] args) {
new Lists();
}
public Lists() {
super("Lists");
setLayout(new FlowLayout());
setBackground(Color.lightGray);
setFont(new Font("Helvetica", Font.BOLD, 18));
List list1 = new List(3, false);
list1.addItem("Vanilla");
list1.addItem("Chocolate");
list1.addItem("Strawberry");
add(list1);
List list2 = new List(3, true);
list2.addItem("Colored Sprinkles");
list2.addItem("Cashews");
list2.addItem("Kiwi");
add(list2);
pack();
show();
}
}
|
This adds an item with the specified label to the end of the list box.
This adds an item with the specified label at the specified position in the list box. All items at that index or later get moved down.
These methods let you attach/detach an ActionListener or an ItemListener. Item events are generated whenever you select or deselect an entry. Action events occur only when you double click an entry or hit RETURN while an entry is selected. They apply only to single-selectable list boxes.
This determines if the list is multiple selectable (true) or single selectable (false).
These methods remove all items from the list.
These return the number of items in the list.
These methods remove entries from the list.
This removes all the items from the starting index through and including the ending index. It is deprecated in Java 1.1; use multiple calls to remove instead.
If the item at the specified index is selected, this deselects it. Otherwise it does nothing.
This returns the label at the specified location.
This returns an array of the labels, in order.
This returns the number of rows (visible height) of the list box, which does not change during the life of the list box. This is in contrast to countItems (or getItemCount), which returns the number of items in the list, which can change over time and be less than or greater than the number of rows. A vertical scrollbar is automatically added if the number of items is greater than the number of rows.
For a single-selectable list, this returns the index of the selected item. It returns -1 if nothing is selected or if the list permits multiple selections.
This returns an array of the indices of all selected items. It works for single- or multi-selectable lists. If no items are selected, a zero-length (but non-null) array is returned.
For a single-selectable list, this returns the label of the selected item. It returns null if nothing is selected or if the list permits multiple selections.
This returns an array of all selected items. It works for single- or multi-selectable lists. If no items are selected, a zero-length (but non-null) array is returned.
This Java 1.1 method returns an array of the selected labels. It returns null if nothing is selected.
This returns the index of the most recent item made visible via makeVisible. Zero is returned if makeVisible has never been called.
This determines if the item at the specified index is currently selected.
If necessary, this scrolls the list to make the item at the given index visible. It is not reliable in all implementations. In particular, this method is erratic in Java 1.0 Windows 95/NT versions.
You can override these lower-level event-processing methods if you want to have the List handle its own events. Item events are generated every time an entry is selected or deselected. Action events are generated when you double click on an entry in a single-selectable list box, or hit ENTER while an entry is selected.
This overwrites the item at the specified index.
This selects the item at the current index. If the list does not permit multiple selections, then the previously selected item, if any, is also deselected. Note that unlike a Choice, a List does not have a select method that lets you supply the label to be selected; you must supply the index.
This permits (true) or prohibits (false) the list from allowing multiple selections.
As a subclass of Component (Section 11.2), List has access to all Component methods. Unlike most of the GUI controls discussed so far, color support for lists is consistent across platforms. Foreground and background colors are supported in Netscape (2, 3, and 4, where released), Internet Explorer (version 3), and Sun's JDK (1.0 and 1.1) on Windows 95/NT, MacOS, and Unix/X11.
Lists are interesting in that they generate two main kinds of events. Item selection events are generated whenever an item is selected or deselected by the user. Calling select from the program does not generate selection events. Action events apply only to single-selectable list boxes, and are generated when the user
double
clicks on an entry or hits RETURN while an entry is selected. In Java 1.0, these are the only two types of events. In Java 1.1, however, the List also gets all mouse, keyboard, or focus events that occur over it.
You can monitor item selection events by watching for Event.LIST_SELECT and Event.LIST_DESELECT. Unfortunately, there is no event-handling helper method for these events, so you have to override handleEvent. Action events, on the other hand, can be monitored in action, just as with buttons and combo boxes (Choice menus). On the other hand, if you are looking for both types of events, you might want to watch for Event.ACTION_EVENT in handleEvent seeing as you have to put code there anyhow. Listing 13.20 shows an example that monitors both types of events, placing the results in textfields (Section 13.8). Figure 13-21 shows the result after activating "Pascal" by clicking twice on it, then selecting but not activating "Java" by clicking once on it.
Listing 13.20
|
|---|
import java.awt.*;
/** A class to demonstrate list selection/deselection
* and action events in Java 1.0.
*/
public class ListEvents1 extends QuittableFrame {
public static void main(String[] args) {
new ListEvents1();
}
private List languageList;
private TextField selectionField, actionField;
private String selection = "[NONE]", action;
/** Build a Frame with list of language choices
* and two textfields to show the last selected
* and last activated items from this list.
*/
public ListEvents1() {
super("List Events in Java 1.0");
setFont(new Font("TimesRoman", Font.BOLD, 16));
add("West", makeLanguagePanel());
add("Center", makeReportPanel());
pack();
show();
}
/** Watches for Event.LIST_SELECT and
* Event.LIST_DESELECT events in textfield.
*/
public boolean handleEvent(Event event) {
if (event.target == languageList) {
if (event.id == Event.LIST_SELECT) {
selection = languageList.getSelectedItem();
selectionField.setText(selection);
System.out.println("Selected " + selection);
return(true);
} else if (event.id == Event.LIST_DESELECT) {
selectionField.setText("");
System.out.println("Deselected " + selection);
return(true);
}
}
return(super.handleEvent(event));
}
/** Reports when list item is activated. Item
* is either (String)object or the list's
* getSelectedItem.
*/
public boolean action(Event event, Object object) {
if (event.target == languageList) {
action = languageList.getSelectedItem();
actionField.setText(action);
System.out.println("Activated " + action);
return(true);
} else
return(false);
}
// Create Panel containing List with language choices.
// Constructor puts this at left side of Frame.
private Panel makeLanguagePanel() {
Panel languagePanel = new Panel();
languagePanel.setLayout(new BorderLayout());
languagePanel.add("North",
new Label("Choose Language"));
languageList = new List(3, false);
String[] languages =
{ "Ada", "C", "C++", "Common Lisp", "Eiffel",
"Forth", "Fortran", "Java", "Pascal",
"Perl", "Scheme", "Smalltalk" };
for(int i=0; i<languages.length; i++)
languageList.addItem(languages[i]);
showJava();
languagePanel.add("Center", languageList);
return(languagePanel);
}
// Creates Panel with two labels and two textfields.
// The first will show the last selection in List; the
// second the last item activated. The constructor puts
// this Panel at the right of Frame.
private Panel makeReportPanel() {
Panel reportPanel = new Panel();
reportPanel.setLayout(new GridLayout(4, 1));
reportPanel.add(new Label("Last Selection:"));
selectionField = new TextField();
reportPanel.add(selectionField);
reportPanel.add(new Label("Last Action:"));
actionField = new TextField();
reportPanel.add(actionField);
return(reportPanel);
}
// Select and show "Java".
private void showJava() {
languageList.select(7);
languageList.makeVisible(7);
}
}
|
In Java 1.1, you have two choices. If you want the List to handle its own events, you can enable AWTEvent.ITEM_EVENT_MASK and AWTEvent. ACTION_EVENT_MASK, then override processItemEvent and processActionEvent to handle item selection and action events. In general, however, it is more flexible to pass the events to an external object to process. You do this by registering an ItemListener via addItemListener and an ActionListener via addActionListener. Listing 13.21 shows an example of the second approach, using the helper classes of Listings 13.22 (an ItemListener) and 13.23 (an ActionListener). Figure 13-22 shows the result, which, except for the frame title, looks and acts just like the Java 1.0 version.
Listing 13.21
|
|---|
import java.awt.*;
import java.awt.event.*;
/** A class to demonstrate list selection/deselection
* and action events in Java 1.1.
*/
public class ListEvents2 extends CloseableFrame {
public static void main(String[] args) {
new ListEvents2();
}
protected List languageList;
private TextField selectionField, actionField;
private String selection = "[NONE]", action;
/** Build a Frame with list of language choices
* and two textfields to show the last selected
* and last activated items from this list.
*/
public ListEvents2() {
super("List Events in Java 1.1");
setFont(new Font("Serif", Font.BOLD, 16));
add("West", makeLanguagePanel());
add("Center", makeReportPanel());
pack();
setVisible(true);
}
// Create Panel containing List with language choices.
// Constructor puts this at left side of Frame.
private Panel makeLanguagePanel() {
Panel languagePanel = new Panel();
languagePanel.setLayout(new BorderLayout());
languagePanel.add("North",
new Label("Choose Language"));
languageList = new List(3);
String[] languages =
{ "Ada", "C", "C++", "Common Lisp", "Eiffel",
"Forth", "Fortran", "Java", "Pascal",
"Perl", "Scheme", "Smalltalk" };
for(int i=0; i<languages.length; i++)
languageList.add(languages[i]);
showJava();
languagePanel.add("Center", languageList);
return(languagePanel);
}
// Creates Panel with two labels and two textfields.
// The first will show the last selection in List; the
// second the last item activated. The constructor puts
// this Panel at the right of Frame.
private Panel makeReportPanel() {
Panel reportPanel = new Panel();
reportPanel.setLayout(new GridLayout(4, 1));
reportPanel.add(new Label("Last Selection:"));
selectionField = new TextField();
SelectionReporter selectionReporter =
new SelectionReporter(selectionField);
languageList.addItemListener(selectionReporter);
reportPanel.add(selectionField);
reportPanel.add(new Label("Last Action:"));
actionField = new TextField();
ActionReporter actionReporter =
new ActionReporter(actionField);
languageList.addActionListener(actionReporter);
reportPanel.add(actionField);
return(reportPanel);
}
/** Select and show "Java". */
protected void showJava() {
languageList.select(7);
languageList.makeVisible(7);
}
}
|
Listing 13.22
|
|---|
import java.awt.*;
import java.awt.event.*;
/** Whenever an item is selected, it is displayed
* in the textfield that was supplied to the
* SelectionReporter constructor
*/
public class SelectionReporter implements ItemListener {
private TextField selectionField;
public SelectionReporter(TextField selectionField) {
this.selectionField = selectionField;
}
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == event.SELECTED) {
List source = (List)event.getSource();
selectionField.setText(source.getSelectedItem());
} else
selectionField.setText("");
}
}
|
Listing 13.23
|
|---|
import java.awt.*;
import java.awt.event.*;
/** Whenever an item is activated, it is displayed
* in the textfield that was supplied to the
* ActionReporter constructor
*/
public class ActionReporter implements ActionListener {
private TextField actionField;
public ActionReporter(TextField actionField) {
this.actionField = actionField;
}
public void actionPerformed(ActionEvent event) {
List source = (List)event.getSource();
actionField.setText(source.getSelectedItem());
}
}
|
In Java 1.0, item selection and action events are the only types of events a List is supposed to generate. In Java 1.1, however, they generate mouse, keyboard, and focus events as well. To demonstrate this, Listing 13.24 shows a variation of the previous example where typing any of the letters in "Java" (upper or lowercase) results in the "Java" entry being selected and made visible. Note the use of an inner class to accomplish this. Instead of creating a separate KeyAdapter class, a nested version is made. Besides being more convenient in such a short class, it lets the showJava method of ListEvents2 remain protected.
Listing 13.24
|
|---|
import java.awt.event.*;
public class ListEvents3 extends ListEvents2 {
public static void main(String[] args) {
new ListEvents3();
}
/** Extends ListEvents2 with the twist that
* typing any of the letters of "JAVA" or "java"
* over the language list will result in "Java"
* being selected
*/
public ListEvents3() {
super();
// Create a KeyAdapter and attach it to languageList.
// Since this is an inner class, it has access
// to nonpublic data (such as the ListEvent2's
// protected showJava method).
KeyAdapter javaChooser =
new KeyAdapter() {
public void keyPressed(KeyEvent event) {
int key = event.getKeyChar();
if ("JAVAjava".indexOf(key) != -1)
showJava();
}
};
languageList.addKeyListener(javaChooser);
}
}
|
| Continue to Section 13.8 (TextFields). | Return to Chapter 13 table of contents. |
|---|