Programmatically Selecting an Item

As with List, it’s useful sometimes to programmatically cause an item in a Combo to be selected without user interaction. Suppose, for example, you want the window to open with a default item already selected, as in Figure 8-4. In that case, you need to force the selection to the proper item.

Opening a window with a selected item

Figure 8-4. Opening a window with a selected item

How do I do that?

Programmatically selecting an item is a Combo is done in the same manner as selecting an item in a List--by making a call to the select() method. This line causes the item in the first position to become selected:;

Since a Combo consists of a text portion in addition to a list portion, you can also cause an item to be selected by setting the text for the item into the text field. This works for Combo objects created with the SWT.READ_ONLY style, but does not work for those created with the SWT.DROP_DOWN style:

c.setText("Item One");

Adding either of these lines of code to Example 8-1 will result in the window opening in the Figure 8-4 state.

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.