gpt4 book ai didi

java - 使用具有完整内容的单个节点元素显示 JTree

转载 作者:行者123 更新时间:2023-12-01 15:55:09 25 4
gpt4 key购买 nike

我有一个节点,其中包含以下格式的所有子节点和属性。

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

childNode2
[
attributes = {childNode2attributes,.....}
value = [1001]
] ......... and some other childnodes like this
]

当我使用 Jtree tree = new Jtree(node); 时它只是为树创建一个根元素,在树的一行中显示所有这些详细信息。

相反,我想在正确的层次结构中显示具有嵌套子节点和属性值的树。有没有内置的方法可以做到这一点?

如果没有内置方法可以执行此操作,我该如何编写代码?

PS:上面显示的节点内容是动态的,不是静态的。

最佳答案

您可以从以下内容开始:

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 是一个复杂的组件 - 请阅读 JTree Swing Tutorial有关如何根据您的具体需求自定义树的更多详细信息。

关于java - 使用具有完整内容的单个节点元素显示 JTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5232690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com