10.7. Adding Checkboxes to Tree Items
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.
Solution
Make your SWT tree support checkboxes by adding the
SWT.CHECK
style, and make your listener listen for
SWT.CHECK
events.
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
Tip
You also can handle check marks with the
setChecked
and getChecked
methods.
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.
Get Eclipse Cookbook 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.