Recipe 10.7 Adding Checkboxes to Tree Items

     

10.7.1 Problem

You need to enable the user to select items in a tree, and when the items are selected, you want them to stay selected until they're specifically deselected.

10.7.2 Solution

Make your SWT tree support checkboxes by adding the SWT.CHECK style, and make your listener listen for SWT.CHECK events.

10.7.3 Discussion

As an example, we can add checkboxes to the tree ( TreeApp at this book's site) that we've been developing over the previous two recipes. To add checkboxes, add the SWT.CHECK style to the tree widget when it's created:

 final Tree tree = new Tree(shell, SWT.CHECK  SWT.BORDER  SWT.V_SCROLL               SWT.H_SCROLL); 

Then listen for SWT.CHECK events in the listener. Here's what that code looks like:

 tree.addListener(SWT.Selection, new Listener( ) {     public void handleEvent(Event event)     {  if (event.detail == SWT.CHECK)   {   text.setText(event.item + " was checked.");   } else   {   text.setText(event.item + " was selected");   }  } }); 

You can see the results in Figure 10-6, where each tree item has a checkbox, and checkbox events are detected .

Figure 10-6. Supporting check marks in an SWT tree
figs/ecb_1006.gif

You also can handle check marks with the setChecked and getChecked methods .


10.7.4 See Also

Recipe 10.5 on creating SWT trees; Recipe 10.6 on handling tree events; Recipe 10.8 on adding images to tree items.



Eclipse Cookbook
Inside XML (Inside (New Riders))
ISBN: 596007108
EAN: 2147483647
Year: 2006
Pages: 232
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net