< Day Day Up > |
Recipe 9.14 Creating Tables9.14.1 ProblemYou have a lot of data you need to present visually, and you want to arrange that data in columns. 9.14.2 SolutionUse an SWT table based on the Table class. SWT tables can display columns of text, images, checkboxes, and more. 9.14.3 DiscussionHere's a selection of the Table class's methods:
As an example (TableApp at this book's site), we'll create a simple table displaying text items that catches selection events. We'll create a new table and stock it with items using the TableItem class, then report which item has been selected in a text widget. Here are some popular TableItem class methods:
Here's how to create the table in this example: Table table = new Table(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); And here's how you can stock it with TableItem objects: for (int loopIndex=0; loopIndex < 24; loopIndex++) { TableItem item = new TableItem (table, SWT.NULL); item.setText("Item " + loopIndex); } All that's left is to handle item selection events, which you can do as shown in Example 9-4; you can recover the item selected with the item member of the event object passed to the handleEvent method. Example 9-4. SWT tablespackage org.cookbook.ch09;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
public class TableClass
{
public static void main(String[] args)
{
Display display = new Display( );
Shell shell = new Shell(display);
shell.setSize(260, 300);
shell.setText("Table Example");
final Text text = new Text(shell, SWT.BORDER);
text.setBounds(25, 240, 200, 25);
Table table = new Table(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
for (int loopIndex=0; loopIndex < 24; loopIndex++) {
TableItem item = new TableItem (table, SWT.NULL);
item.setText("Item " + loopIndex);
}
table.setBounds(25, 25, 200, 200);
table.addListener(SWT.Selection, new Listener( )
{
public void handleEvent(Event event)
{
text.setText("You selected " + event.item);
}
});
shell.open( );
while (!shell.isDisposed( ))
{
if (!display.readAndDispatch( ))
display.sleep( );
}
display.dispose( );
}
} The results appear in Figure 9-9. When you select an item in the table, the application indicates which item was selected. Figure 9-9. A simple tableThat's fine up to a point, but this rudimentary example just gets us started with tables (in fact, this simple version looks much like a simple list widget). To add columns, check marks, images, and more, see the following recipes.
9.14.3.1 Eclipse 3.0In Eclipse 3.0, the SWT table widget supports setting the foreground and background colors of individual cells. In addition, the Table widget enables you to set the font for a row or an individual cell. 9.14.4 See AlsoRecipe 9.15 on creating table columns; Recipe 9.16 on adding check marks to table items; Recipe 9.17 on enabling and disabling table items; Recipe 9.18 on adding images to table items. |
< Day Day Up > |