Determining the Checked Item(s)

If you use the SWT.CHECK style, you need to determine what item or items have been checked by the user.

How do I do that?

You can determine whether a particular item is checked or unchecked by calling the TreeItem getChecked( ) method. The following code loops through the Tree and determines the status of each TreeItem it finds:

TreeItem[] tia = t.getItems( );
for(int i=0; i<tia.length;i++){
    if(tia[i].getChecked( )){
       // take some action
       System.out.println("Checked");
    }
    TreeItem[] children = tia[i].getItems( );
    for(int n=0; n<children.length;n++){
        if(children[i].getChecked( )){
             // take some action
             System.out.println("Checked");
            }
        }
}

SWT.CHECK-style Tree objects are very useful when you need to allow the user to make multiple selections from the tree, but don’t want the extra overhead associated with the SWT.MULTI mode (which wouldn’t be appropriate if using the selected TreeItem to take some action such as populating a list).

Note

Admittedly, this code is specific to our tree, which has only one level of children. Multiple layers of children would require recursion to avoid multiple nested if statements and for loops.

As with all the SWT widgets, Tree is very simple to create and use, especially if you compare it to the SWING JTree, which has a reputation for being very hard to configure and use.

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.