Determining the Selected Items

As you can see, adding a list to a window and populating it with items is a fairly simple exercise, requiring mastery of only a few simple methods. Most of the methods of the List class deal with interacting with the list and its items in some meaningful fashion. The interaction that we will almost always need to perform is to obtain the item or items that the user has selected from the list.

Note

This is what lists are all about, after all is said and done.

How do I do that?

Consider the following code:

l.addSelectionListener(new SelectionListener( ) {
    public void widgetSelected(SelectionEvent e) {
        String selected[] = l.getSelection( );
        System.out.println(selected[0]);
    }
    public void widgetDefaultSelected(SelectionEvent e) {
    }
});

Here a SelectionListener is created and added to the list. In the widgetSelected( ) method, which is called each time the user clicks an item in the list, you call getSelection( ) to print out the item selected to the Console.

Recall that a list may enable the user to select more than one item, if it is an SWT.MULTI-style List . getSelection( ) returns an array of strings that contain every item that is currently selected. In this example, only the 0 position is referenced when the print to the Console is performed. Why? Since this is a single selection list only one position in the string array is populated—position 0.

Get SWT: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.