< Day Day Up > |
7.5 Working with ListsAnother popular control is the list control, represented by the SWT List class. We'll take a look at an example using this control and how to recover selections made in the control. Here are the styles you can use with lists:
In this case, we're going to fill the entire shell with a list control, using the fill layout. Here's what that looks like—note that we're also using the List class's add method to add items to the list: public class Ch07_04 { public static void main (String [] args) { Display display = new Display ( ); Shell shell = new Shell (display); shell.setText("List Example"); shell.setSize(300, 200); shell.setLayout(new FillLayout(SWT.VERTICAL)); final List list = new List (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); for (int loopIndex = 0; loopIndex < 100; loopIndex++){ list.add("Item " + loopIndex); } . . . Now we can recover the selected items using a selection listener and the getSelectionIndices method. This method returns an int array of the selected indices in the list control, and we can display those indices in the console, as you see in Example 7-4. Example 7-4. Using listspackage org.eclipsebook.ch07;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
public class Ch07_04 {
public static void main (String [] args) {
Display display = new Display ( );
Shell shell = new Shell (display);
shell.setText("List Example");
shell.setSize(300, 200);
shell.setLayout(new FillLayout(SWT.VERTICAL));
final List list = new List (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
for (int loopIndex = 0; loopIndex < 100; loopIndex++){
list.add("Item " + loopIndex);
}
list.addSelectionListener(new SelectionListener( )
{
public void widgetSelected(SelectionEvent event)
{
int [] selections = list.getSelectionIndices ( );
String outText = "";
for (int loopIndex = 0; loopIndex < selections.length;
loopIndex++) outText += selections[loopIndex] + " ";
System.out.println ("You selected: " + outText);
}
public void widgetDefaultSelected(SelectionEvent event)
{
int [] selections = list.getSelectionIndices ( );
String outText = "";
for (int loopIndex = 0; loopIndex < selections.length; loopIndex++)
outText += selections[loopIndex] + " ";
System.out.println ("You selected: " + outText);
}
});
shell.open ( );
while (!shell.isDisposed ( )) {
if (!display.readAndDispatch ( )) display.sleep ( );
}
display.dispose ( );
}
}
You can see the results in Figure 7-4, where we're displaying the selections the user made in the list control. Figure 7-4. Selecting items in a list |
< Day Day Up > |