Adding Items to a List
You can use the setItems()
method to add items to a list with
only a single method call. This keeps code clutter to a minimum and
makes for cleaner implementation.
How do I do that?
To populate the list with only a single method call, you must first
create an array of String
objects that hold the
items to be added:
String items[] = {"Item One", "Item Two", "Item Three", "Item Four", "Item Five"};
You then call the setItems( )
method, passing it
the String
array:
l.setItems(items);
Changing ListExample
to use this approach will
result in a window identical to Figure 7-1, as
shown in Example 7-2.
Example 7-2. Using setItems( ) to populate a list
import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.*; public class ListExample { Display d; Shell s; ListExample( ) { d = new Display( ); s = new Shell(d); s.setSize(250,250); s.setImage(new Image(d, "c:\\icons\\JavaCup.ico")); s.setText("A List Example"); String items[] = {"Item One", "Item Two", "Item Three", "Item Four", "Item Five"}; final List l = new List(s, SWT.SINGLE | SWT.BORDER); l.setBounds(50, 50, 75, 75); l.setItems(items); s.open( ); while(!s.isDisposed( )){ if(!d.readAndDispatch( )) d.sleep( ); } d.dispose( ); } }
If you have large lists, this method will result in code that is more
readable than will using an add( )
call for each
item.
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.