Getting and Setting Text in the Text Portion of the Combo

You have already worked with getText( ) and setText( ) in the preceding sections, but that was in the context of an SWT.READ_ONLY combo. In an SWT.DROP_DOWN style combo, setText( ) works a little differently and bears re-examination.

In the preceding examples, setText( ) was used as a method of selecting an item in the list portion of the combo. With a SWT.READ_ONLY combo, that approach works fine, but in an SWT.DROP_DOWN -style combo, that approach no longer works. When you perform a setText( ) action on an SWT.DROP_DOWN combo, the text portion of the combo will reflect the change, but you must take an additional action to force an item to actually become selected.

Note

What difference does it make, as long as the item appears in the text portion? It matters if you use a method that returns the index value of the selected item.

How do I do that?

As shown earlier, the following code can be used in a READ_ONLY combo to force an item to become selected:

final Combo c = new Combo(s, SWT.READ_ONLY);
c.setBounds(50, 50, 150, 65);
String items[] = {"Item One", "Item Two", "Item Three", "Item Four", "Item Five"};    
c.setItems(items);
c.setText("Item One");
System.out.println(c.getSelectionIndex( ));

Executing this code will cause Item One to be selected in the list. The call to getSelectionIndex( ) will cause the index value 0 (remember the list is zero-indexed) to be printed to the Console.

Contrast that code with this:

final Combo ...

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.