开发者

Indexing JTree nodes

I would like to create an index (1, 1.开发者_Python百科2, 1.3, 2.1 etc.) for each node of a JTree at the time of adding the new node,

i.e.

root
|
 ---1 node
|
 ---2 node
    |
     ---2.1 node 

Does anybody have an idea how I can do it? Thank you in advance for any answers.


As you add a node, find the current number of nodes in that level and your index of your new node is the count plus 1.


Since you didn't tell us, if you have implemented your own TableModel, I assume, that you work with a standard JTree and the default model. A method that retrieves the index of a Node as a String would look like this:

public String getNodeIndex(JTree tree, TreeNode node) {
    TreeNode root = (TreeNode) tree.getModel().getRoot();
    if (node == root) {
        return "";
    }
    TreeNode parent = node.getParent();
    if (parent == null) {
        return null;
    }
    String parentIndex= getNodeIndex(tree, parent);
    if (parentIndex == null) {
        return null;
    }
    return parentIndex+"."+parent.getIndex(node);
}

This code should work as long as you don't build cycles into your tree, as if works recursively up to the root.


With complexe UI components, it is better to distinguish the data model and the rendering. As a consequence, I suggest you implement a TreeModel which returns for example Nodes objects which may contain the integer for its level and you also implement a TreeCellRenderer which makes the rendering of the node.

The index may be either computed at each rendering using parents node which can be asked to the model of the information could be cached into the node. You can have a look here on how to implement a custom TreeModel : http://download.oracle.com/javase/tutorial/uiswing/components/tree.html#data

If you need to do things when parent nodes are clicked, you can use Tree-Will-Expand listeners (also referenced in the tutorial)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜