开发者

Display JTree using a single node element having full content

开发者 https://www.devze.com 2023-02-15 07:28 出处:网络
I have a single node that has all the child nodes and attributes in the following format. node =Root[ attributes = {rootattribute1, rootattribute2,...},

I have a single node that has all the child nodes and attributes in the following format.

node =   Root[
         attributes = {rootattribute1, rootattribute2,...}, 
         value = [100,
                childNode1
                [
                attributes = {childNode2att1,.....}
                value = [1001]  
                ]

                childNode2
                [
           开发者_开发百科     attributes = {childNode2attributes,.....}
                value = [1001]  
                ] ......... and some other childnodes like this
                ]

When I use Jtree tree = new Jtree(node); It is creating just a single rootelement for the tree showing all these details within a single row of a tree.

Instead I want to display the tree in the correct hierarchy with nested child nodes and atrribute values. Is there any inbuilt method to do this ?

If there is no inbuilt method to do this how do I write the code for this ?

PS: the node content displayed above is dynamic and is not static.


You can start with something like:

import javax.swing.*
import javax.swing.tree.*

class Root {
    def attributes = []
    def children = []
    def value = 0

    def String toString() { 
        "[${value}] attributes: ${attributes} children: ${children}" 
    }
}

def createTreeNode(node) {
    def top = new DefaultMutableTreeNode(node.value)
    for (attr in node.attributes) {
        top.add(new DefaultMutableTreeNode(attr))
    }
    for (child in node.children) {
        top.add(createTreeNode(child))
    }   
    top
}

root = new Root(
    attributes: ['rootattribute1', 'rootattribute2'], 
    value: 100,
    children: [
        new Root(
            attributes: ['childNode2att1'],
            value: 1001),
        new Root(
            attributes: ['childNode2attributes'],
            value: 1002),    
    ])


frame = new JFrame('Tree Test')
frame.setSize(300, 300)
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
jtree = new JTree(createTreeNode(root))
frame.add(jtree)
frame.show()

JTree is a sophisticated component - please read the JTree Swing Tutorial for more details on how to customize the tree for your exact needs.

0

精彩评论

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