PDA

View Full Version : Tree: How to add a selection change event listener



HerrB
8 Jun 2009, 9:24 AM
For starters (like me):
How to add a selection change event listener to a Tree:

Only single selection:


Tree objTree = new Tree();
objTree.setSelectionMode(SelectionMode.SINGLE);

objTree.setSelectionModel(new TreeSelectionModel() {
@Override
protected void onSelectChange(TreeItem objItem, boolean blnSelect) {
if (blnSelect) {
System.out.println(objItem.getId());
}

super.onSelectChange(objItem, blnSelect);
}});


or



Tree objTree = new Tree();
objTree.setSelectionMode(SelectionMode.SINGLE);

objTree.addListener(Events.SelectionChange, new Listener<TreeEvent>() {
public void handleEvent(TreeEvent objEvent) {
List<TreeItem> lstSelectedItems = objEvent.getSelected();

if (lstSelectedItems.size() > 0) {
TreeItem objItem = lstSelectedItems.get(0);

if (objItem != null) {
System.out.println(objItem.getId());
}
}
}});


Multiple selection:


Tree objTree = new Tree();
objTree.setSelectionMode(SelectionMode.MULTI);

objTree.addListener(Events.SelectionChange, new Listener<TreeEvent>() {
public void handleEvent(TreeEvent objEvent) {
List<TreeItem> lstSelectedItems = objEvent.getSelected();

if (lstSelectedItems.size() > 0) {
for (TreeItem objItem : lstSelectedItems) {
if (objItem != null) {
System.out.println(objItem.getId());
}
}
}
}});


Wrong, as SelectionChange doesn't work with SelectionListener (yes, makes sense, but for beginners you'll try everything):

objTree.addListener(Events.SelectionChange, new SelectionListener<TreeEvent>() {

Wrong, as SelectionChangedListener only works using a TreeModel and not with a simple Tree:

objTree.addListener(Events.SelectionChange, new SelectionChangedListener<TreeModel>() {

In the GXT FAQ it says:

How to handle selection events on a Tree ?
Use TreeBinder.addSelectionChangedListener(..)

Err, this should work, if you have a Tree bound to a data store (yes, makes sense, as it is a TreeBinder, I know... ;) ) which IMHO I don't have, if I fill the tree using addItem - or? If it works anyway, a full working example would be nice...

Feedback is appreciated, especially, If I've got something wrong...

Regards,

HerrB