Selecting Items Programmatically

Of course, if table items are selectable, there must be a way to programmatically determine which item is selected, or to cause it to be selected without user intervention. For example, when a Table is first displayed, no items are selected but it is often desirable to cause the table to open with the first item highlighted, or to highlight some other item based on program conditions.

How do I do that?

When it comes to working with selected items, Table generally works like lists, and as with the List class, a number of methods are provided that enable you to perform this task.

The getSelection() method will return an array of TableItem objects that are currently selected:

TableItems[] t = t.getSelection( );

This is particularly useful if the table is of the multiple-selection type, since it enables you to get all selected items in a single method call.

Also, for multiple-selection tables, getSelectionIndices() returns an array of int values that specify which TableItems are selected, based on a zero index:

int[] selected = t.getSelectionIndices( );

Calling getSelectionIndices( ) against a table in the state shown in Figure 12-4 will return 0 and 2 in the int array.

For single-selection tables, you can use getSelectionIndex() to return the index of the currently selected item:

int selected = t.getSelectedIndex( );

Once you have a reference to the item that is selected, you can perform other tasks such as getting values from particular columns. A later ...

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.