< Day Day Up > |
Recipe 8.8 Creating List Widgets8.8.1 ProblemYou need to display multiple items from which the user can select. 8.8.2 SolutionUse a list widget, which can display lists of selectable items. Here's a selection of the most popular list widget methods:
8.8.3 DiscussionAs an example, we'll add a multiple-selection list widget to a shell and get the user's selections with the getSelectionIndices method; this example is named ListApp and can be found at this book's site. Here's how to add a list widget to a shell: import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.events.*; public class ListClass { public static void main (String [] args) { Display display = new Display ( ); Shell shell = new Shell (display); shell.setText("List Example"); shell.setSize(300, 200); final List list = new List (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); list.setBounds(40, 20, 220, 100); for (int loopIndex = 0; loopIndex < 9; loopIndex++){ list.add("Item Number " + loopIndex); } . . . You can add a selection listener to the list widget, as shown in Example 8-6. In this example, we'll use the list widget's getSelectionIndices method to get an int array of the selected indices in the list widget. We'll display those selections in a text widget, as you see in the code. Example 8-6. Using list widgetspackage org.cookbook.ch08;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
public class ListClass {
public static void main (String [] args) {
Display display = new Display ( );
Shell shell = new Shell (display);
shell.setText("List Example");
shell.setSize(300, 200);
final List list = new List (shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
list.setBounds(40, 20, 220, 100);
for (int loopIndex = 0; loopIndex < 9; loopIndex++){
list.add("Item Number " + loopIndex);
}
final Text text = new Text(shell, SWT.BORDER);
text.setBounds(60, 130, 160, 25);
list.addSelectionListener(new SelectionListener( )
{
public void widgetSelected(SelectionEvent event)
{
int [] selectedItems = list.getSelectionIndices ( );
String outString = "";
for (int loopIndex = 0; loopIndex < selectedItems.length;
loopIndex++) outString += selectedItems[loopIndex] + " ";
text.setText("Selected Items: " + outString);
}
public void widgetDefaultSelected(SelectionEvent event)
{
int [] selectedItems = list.getSelectionIndices ( );
String outString = "";
for (int loopIndex = 0; loopIndex < selectedItems.length; loopIndex++)
outString += selectedItems[loopIndex] + " ";
System.out.println ("Selected Items: " + outString);
}
});
shell.open ( );
while (!shell.isDisposed ( )) {
if (!display.readAndDispatch ( )) display.sleep ( );
}
display.dispose ( );
}
} The results appear in Figure 8-7, where the code is displaying the selections the user has made. Figure 8-7. Using a list widget |
< Day Day Up > |