• Post Reply Bookmark Topic Watch Topic
  • New Topic

sorting node position in JTree

 
Miana Husada
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
I want to rearrange node position in JTree according to the id which has been saved in each node.
For example:
Node A has 3 children: B(id=9), C(id=2), D(id=5)
the displayed tree should be: A has 3 children: Node C at index 0, node D at index 1, Node B at index 2.
could anyone please help me?
thanks a lot,
Mia
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just did this method to move the currently selected child node up or down within its parent. It assumes single select mode and tree nodes are (or extend) DefaultMutableTreeNode.

The JTree remove and insert methods do the moving. The rest just make sure it is ok to move.
This always inserts the node in collapsed state. I'd like to find a way to preserve the state of the node I'm moving and all of its children.
 
Anthony Yulo
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

this code ensures that when you add a node, the tree is automatically sorted...basically you compare all of the children IDS of the parent and with the node ID of the node you are currently adding... and then when node ID is less than the current traversed child ID then insert that before the current child...
i haven't compiled this code.. its only an idea...so make the proper corrections if there are errors in it...
 
Anthony Yulo
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
insert the line:
parent.insert(node,parent.getChildCount-1);
after the end braces of the for loop.... so if the id is greater than all of the child nodes, it will insert on the last position...
another thing, replace the yellow smiley face with a semicolon and a closing parenthesis i.e "; )" andthe green face with a colon and the letter p i.e. ": p"
 
Anthony Yulo
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also please add "break;" after the last line inside the if statement.....
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!