7.4 Class List
7.4.1 Example

7.4.2 List Hierarchy

7.4.3 List Styles
Style | Description |
|---|
SWT.MULTI | Create a list that can have multiple items selected | SWT.SINGLE | Create a list that can have only one item selected |
7.4.4 List Events
Event | Description |
|---|
SWT.Selection | The user selected an item | SWT.DefaultSelection | The user double-clicked on an item |
Lists allow the user to select one or more strings from a collection of strings. The strings are presented to the user in a single column.
Lists provide a rich API to manipulate their contents. Because List allows duplicates, the most useful methods in the class are index-based, because using indices allows you to specify exactly which item in the list will be referenced.
|
At one time, before icons ruled the user interface, lists were ubiquitous. Programs used them to show most kinds of data. These days, lists are uncommon. For example, lists are sometimes used to show key words in a Help dialog, but tables are used for almost everything else. If your application needs to display a list of strings, use a list. Otherwise, you should consider using a table (see the section Classes Table, TableItem, and TableColumn). In particular, you should use a table if you want to display an icon beside each item. |
In the descriptions that follow, the term item is used interchangeably with string. This is done on purpose because some of the concepts and behaviors that are first mentioned in class List, which uses String, also apply to class Table, which uses TableItem.
7.4.5 Single- and Multiselect Lists
There are two kinds of lists in SWT: single-select and multiselect. Lists that allow only a single item to be selected at a time are called single-select lists. They are constructed by using the style SWT.SINGLE. Similarly, lists that allow multiple items to be selected are called multiselect lists and can be constructed by specifying the style constant SWT.MULTI.
Just like text controls, lists can include scroll bars and borders. The following code fragment creates a single-select list that has a border and vertical and horizontal scroll bars.
List list = new List (SWT.SINGLE | SWT.BORDER |
SWT.V_SCROLL | SWT.H_SCROLL);
7.4.6 Setting Items
Typically, the contents of a list are initialized using setItems(). To change a single item, use setItem(). Indexing operations that get and set items throw an exception when an index is out of bounds.
setItems(String[] items)
Sets the items. This method removes the previous items from the list and replaces them with the new items. The selection is cleared, and the list is scrolled to the top. setItem(int index, String string)
Sets the item at an index. This method replaces the previous item with the new string. If the index is out of range, an IllegalArgumentException ("Index out of bounds") is thrown. getItems()
Returns the items, which is an array of strings. The array that is returned is a copy of the contents. Modifying this array will not affect the control. getItem(int index)
Returns the item at an index. If the index is out of range, an IllegalArgumentException ("Index out of bounds") is thrown. getItemCount()
Returns the number of items in the control.
It is much more efficient to reset the contents of a list using setItems(), rather than updating each individual item using setItem(). The setItem() method is intended for those times when you have a list whose contents are mostly correct and you need to change only a few items.
7.4.7 Item Height
You can find out the height of an item within a list using getItemHeight().
getItemHeight()
Returns the height in pixels of an item in the control. This value can be different from height of the font that is in use by the control, because some platforms include spacing between items.
The getItemHeight() method is mostly used to compute the initial size of a list. Refer to Lines and the Line Delimiter in Class Text for an example that computes the initial size of a text control. The code to do this for List is equivalent but uses getItemHeight() instead. Here are the relevant changes:
int height = rows * list.getItemHeight();
int width = columns * fm.getAverageCharWidth();
list.setSize(list.computeSize(width, height));
7.4.8 Adding Items
Items can also be added to a list one at a time using the add() method. Methods that add items throw an exception when an index is out of bounds.
add(String string)
Adds an item at the end of the list. This is the same as add(string, list.getItemCount()) but is slightly faster on some platforms. add(String string, int index)
Adds the item to the list at the given index. The operation is equivalent to performing the following steps.
The size of the list is increased by one.
All items in the list between the index and the original end of the list are shifted one position toward the end.
The new string is stored at the index (i.e., setItem(index, string)).
In other words, the string is inserted into the list immediately before the item that was originally at the given index. For example, add("New Item", 5) causes "New Item" to become the fifth item in the list; the item that was the fifth item becomes the new sixth item, and so forth. The valid range for the index parameter is 0..N, where N is the number of items in the list. Using an index of zero makes the string the first element in the list. Using an index of N makes the string the last element in the list. If the index is out of range, an IllegalArgumentException ("Index out of bounds") is thrown.
Note that adding all of the items one at a time is much slower than setting all of the items at once. Of course, if you are adding only a couple of items to a preexisting list, using add() is more efficient than resetting the entire contents.
7.4.9 Removing Items
Items are removed using remove() or removeAll(). As was true for the add() methods, methods that remove items throw an exception when an index is out of bounds.
remove(int index)
Removes the item at the index. If the index is out of range, an IllegalArgumentException ("Index out of bounds") is thrown. remove(int start, int end)
Removes items from start to end, inclusive. If an index is out of range, an IllegalArgumentException ("Index out of bounds") is thrown. remove(int[] indices)
Removes items using an array of indices. If an index is out of range, an IllegalArgumentException ("Index out of bounds") is thrown. remove(String string)
Removes the first occurrence of the string from the list. Note that the string must be an exact, case-sensitive match for one of the elements of the list. If the string is not found, an IllegalArgumentException ("Argument not valid") is thrown. removeAll()
Removes all the items from the list.
The following code fragment initializes a list to contain the strings "Red", "Green", and "Blue", then removes the item "Green".
list.setItems(new String[] {"Red", "Green", "Blue"});
list.remove("Green");
It is much faster to remove a range of items than to remove items one at a time. Note that removeAll() and setItems(new String[0]) are equivalent operations.
7.4.10 The Selection
Lists provide many different methods to set the selection. Most of these methods are index-based, and all of them scroll to show the new selection. Unlike methods that add and remove items, methods that set the selection ignore indices that are out of bounds.
|
Early versions of SWT attempted to be consistent with respect to bounds checking for methods that took indices by always checking bounds and throwing an exception. The result was a disaster. It was discovered that many programs routinely expected to be able to pass indices that were out of range for certain kinds of operations. As a result, we ended up taking a rather pragmatic approach to bounds checking, throwing exceptions only where the consistency of the list would be affected. For example, selection and range operations (such as setting the thumb of a scroll bar) do not throw exceptions, instead attempting to do something reasonable when a value is out of range. Operations that add, get, set, or remove items can throw "Index out of bounds" exceptions. |
setSelection(int index)
Selects the item at the given index. Indices that are out of range are ignored. Any previous selection is cleared. The control is scrolled to bring the new selection to the attention of the user. If the control has a focus indicator, the focus indicator is assigned to the new selection. |
As you might expect, methods that set properties first clear the old value, then set the new one. In addition, any action that is necessary to bring the new value to the attention of the user is performed. For example, when setSelection() is called for a list control, not only is the old selection cleared and the new selection assigned but the control is also scrolled so that the new selection can be seen. The select() method (described later in this section) simply selects the item without scrolling or affecting the previous selection. |
setSelection(int start, int end)
Selects all items in the range start to end, inclusive. If the control is single-select and the range contains more than one item, all of the indices are ignored. Once the previous selection has been cleared and the new items have been selected, the control is scrolled to show the new selection, and the focus indicator is assigned. setSelection(int[] indices)
Selects items using an array of indices. If the array is empty, the selection is cleared. If the control is single-select and the array contains more than one item, all of the indices are ignored. Once the previous selection has been cleared and the new items have been selected, the control is scrolled to show the new selection, and the focus indicator is assigned. setSelection(String[] strings)
Selects items using an array of items. This method behaves the same as though setSelection(indices) were called using an array of indices computed by determining the index within the control of each item in the array of strings. getSelection()
Returns the selection as an array of items. Note that this is an array of strings for a list control. This is a copy so that modifying the array has no effect on the control. getSelectionCount()
Returns the number of selected items. getSelectionIndex()
Returns the index of the item that is selected, based on the following rules. If no items are selected, –1 is returned. If the item that has the focus indicator is selected, that index is returned. Otherwise, the index of the first selected item is returned.
getSelectionIndices()
Returns the selection as an array of indices. This is a copy so that modifying the array has no effect on the control. isSelected(int index)
Returns true if the item at the index is selected. If the item is not selected or the index is out of range, false is returned.
7.4.11 Deselecting and Selecting Items
The methods in this section differ from the setSelection() methods in two significant ways.
They do not clear the previous selection before acting. They do not cause the control to scroll.
Because these methods are operations on the selection, when an index is out of range, an exception is not thrown.
deselect(int index)
Deselects the item at the given index. Indices that are out of range are ignored. deselect(int start, int end)
Deselects items in the range start to end, inclusive. Indices that are out of range are ignored. deselect(int[] indices)
Deselects items using an array of indices. Indices that are out of range are ignored. deselectAll()
Deselects all items in the control. select(int index)
Selects the item at the given index. Indices that are out of range are ignored. select(int start, int end)
Selects items in the range start to end, inclusive. Indices that are out of range are ignored. If the control is single-select and the range contains more than one item, all of the indices are ignored. select(int[] indices)
Selects items using an array of indices. Indices that are out of range are ignored. If the control is single-select and the array contains more than one item, all of the indices are ignored. selectAll()
Selects all items in the control. If the control is single-select, the selection is not changed.
7.4.12 Scrolling
Scrolling in a list has the same API as scrolling in a text control. Instead of the top index being the index of a line of text, it is the index of an item in List.
setTopIndex(int index)
Scrolls to show the item indicated by the index parameter at the top of the control. Indexing starts at zero. If the index is out of range, the control scrolls to show the closest index that is within range. Depending on both the platform and the number of items, it may not be possible for the particular item to be displayed at the top of the control; this can happen if the platform does not allow the control to scroll so that white space follows the last item. getTopIndex()
Returns the line that is at the top of the control. The top index can change for many reasons other than calling setTopIndex(). For example, setSelection() can scroll the control to show the new selection, or the user can scroll the control. showSelection()
Scrolls to show the selection. If the selection is already visible, nothing happens. Because the control may be scrolled, this method is useful to bring the selection to the attention of the user. If multiple items are selected, the control is scrolled so that at least part of the selection is visible.
7.4.13 Searching
Lists provide a number of searching operations that allow you to find the index of a string within a list.
indexOf(String string)
Returns the zero-based index of the string. This is the same as calling indexOf(string, 0). indexOf(String string, int start)
Returns the zero-based index of the string, starting at the start index. If the string is not found, –1 is returned.
7.4.14 List Events
SWT.Selection (SelectionEvent)
The SWT.Selection event (typed event SelectionEvent) is sent whenever the user selects an item with the mouse or the keyboard. The selection event for List contains meaningful values in only the display, widget, and type fields.
SWT.DefaultSelection (SelectionEvent)
The SWT.DefaultSelection event (typed event SelectionEvent) is sent whenever the user performs the platform-specific operation that indicates default selection. On most platforms, default selection occurs when the user double-clicks on an item or presses the <Enter> key. The default selection event for List contains meaningful values in only the display, widget, and type fields.
Using SWT.Selection to Print the Current Selection
The following example uses SWT.Selection to print the current selection of the list when the user selects items. The example uses add() instead of setItems() because the number of items is small.
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
int style =
SWT.MULTI|SWT.BORDER|SWT.H_SCROLL|SWT.V_SCROLL;
final List list = new List(shell, style);
for (int i=0; i<128; i++) {
list.add("Item " + i);
}
list.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
String[] selection = list.getSelection();
System.out.print("{");
for (int i = 0; i < selection.length; i++) {
System.out.print(selection[i]);
if (i < selection.length - 1) {
System.out.print(" ");
}
}
System.out.println("}");
}
});
list.setSize(200, 200);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
display.dispose();
}
|