Causing an Item to Appear Selected

The List class also provides methods that enable you to cause an item or items to become selected without user interaction with the list.

How do I do that?

You can use two methods when you need to programmatically select an item before the user selects items using a mouse click. To cause an item at a specified index position to become selected, use the select( ) method:

l.select(1);

Tip

Remember that lists are zero-indexed.

You can also select a range of items, by using another version of select( ), one that accepts two int values—one to specify where to start selecting and the other to specify where to stop. This code selects the second through fifth:

l.select(1,4);

What about...

the times when you want to select an item by the String display value? There isn’t a direct method for that purpose, but you can always combine methods to accomplish the task. In this code, you use the indexOf() method to search the list for the first item that matches the passed String, then pass the index returned to the select( ) method to perform the selection:

l.select(l.indexOf("Item Two"));

Tip

In a single selection listbox, a call to select( ) causes any items that are already selected to become deselected, even if the previously selected items were selected via user input. Programmatically selecting items takes a bit of thought as to how the user will perceive the action.

You can also select items using another method—setSelection(). setSelection( ) provides functional ...

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.