Re: [Java-gnome-developer] Question: TreeView & TreeStore and Listeners
Brought to you by:
afcowie
From: Luca De R. <pie...@li...> - 2004-02-03 21:27:56
|
Il mar, 2004-02-03 alle 21:20, Alex Moreno ha scritto: > The last days i've been working with trees. > > I've found a way of getting selected rows. I don't know is this is a > correct way of doing it. I'd much appreciate corrections o opinions. The > way which i'm discovering which row is selected is iterating over the > tree until i foun the row. Then, i make all the desired work: > > TreeIter iter = tree.getModel().getFirstIter(); > Boolean exit = Boolean.False; > do{ > //if the searched row is equals the actual row > if (win.tree.getSelection().getSelected(iter)) { > System.out.println(tree.getModel().getValue(iter,win.dataBlock)); > exit = Boolean.TRUE; > > } > }while(tree.getModel().moveIterNext(iter) && !exit.booleanValue())) > > where > DataBlockString dataBlock = new DataBlockString(); > [....] > DataBlock data[] = new DataBlock[] { dataBlock, dataBlock2, ...} > > > As I said, corrections a comments are wellcome :-). I would simply use: if ((event.getType()) == TreeSelectionEvent.Type.CHANGED) { TreeIter anIter = treeStore.getFirstIter(); while (!(anIter == null && selection.getSelected(anIter))) { anIter = treeStore.getNextIter(anIter); } if (anIter != null) { rowSelected = Integer.parseInt((treeStore.getPath(anIter)).toString()); //System.out.println("row n." + rowSelected + " selected"); } else rowSelected = -1; } So you can get the selected row simply getting the rowSelected int. Also note that since the CHANGED event is only a hint, you have to expect that it's possible that 0 rows are actually selected. I haven't tried your code, but for the above reason it could launch a NullPointerException when it reaches the end of the tree rows without finding a selected one (or when performed on an empty treeview), so you have to check that anIter != null. I also have a smart algorithm to remove multiple selected rows from a treeview. It is: public void removeButtonClicked() { TreePath path = new TreePath("0"); //stop at the end of the list while (store.getIter(path) != null) { //remove contiguous selected rows while (mySelection.getSelected(path)) store.removeRow(store.getIter(path)); //step ahead until an unselected row or null is found while (!mySelection.getSelected(path) && store.getIter(path) != null) path.next(); } } As you can see there are 3 while cycles in it. Does anyone have a nicer/faster algorithm ? -- Luca De Rugeriis <pie...@li...> |