10.5. Creating SWT Trees
Problem
You need to display data items in a hierarchical, collapsible-and-expandable form.
Solution
Use an SWT tree widget, based on the Tree and
TreeItem classes.
Discussion
As an example, we’ll create a tree
(TreeApp at this book’s site)
that contains several levels of items. Here is a selection of useful
Tree methods:
-
void addSelectionListener(SelectionListener listener) Adds the listener to the collection of listeners who are notified when the tree’s selection changes
-
void deselectAll( ) Deselects all selected items in the tree
-
TreeItem[] getItems( ) Returns an array of items contained in the tree item
-
TreeItem[] getSelection( ) Returns an array of
TreeItemobjects that are selected in the tree-
int getSelectionCount( ) Returns the number of selected items in the tree
-
void selectAll( ) Selects all the items in the tree
-
void setSelection(TreeItem[] items) Sets the tree’s selection to be the given array of items
The code in the TreeApp example creates a tree
in this way:
final Tree tree = new Tree(shell, SWT.BORDER | SWT.V_SCROLL |
SWT.H_SCROLL);
tree.setSize(290, 260);The items you add to a tree such as this are objects of the
TreeItem class; here’s a
selection of TreeItem methods:
-
boolean getChecked( ) Returns
trueif the tree item is checked,falseotherwise-
boolean getGrayed( ) Returns
trueif the tree item is grayed,falseotherwise-
int getItemCount( ) Returns the number of items contained in the tree item
-
TreeItem[] getItems( ) Returns an array of
TreeItem ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access