Getting the Value of the Selected Item

The main programmatic interaction you must have with a Combo, once created, is in the realm of determining which item the user has selected.

How do I do that?

Obtaining the selected item is much easier with a Combo than it is with a List, for a couple of reasons. First, since all combos are single-selection, you need not worry about parsing multiple selection arrays to determine the item(s) selected.

The second reason stems from the combo’s dual use of a text field in conjunction with the list. When the user selects an item from the list, the text portion of the Combo changes to show the item selected. To determine what that item is, use this:

String item = c.getText( );

This returns the String value of the selected item. If you need the index value, you use this:

int i = c.getSelectionIndex( );

getSelectionIndex() returns the index value (zero-referenced) of the selected item, or -1 if no item has been selected.

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.