我想从二维对象数组创建一个JTree,该数组将从SQL查询导入。这就是SQL表的样子:
这是对象的示例:
Object[][] table = {
{1, 0, "Root"}, //i=0
{2, 1, "Node2"}, //i=1
{3, 1, "Node3"}, //i=2
{4, 1, "Node4"}, //i=3
{5, 4, "Node5"}, //i=4
{6, 4, "Node6"}, //i=5
{7, 4, "Node7"}, //i=6
{8, 1, "Node8"}, //i=7
{9, 1, "Node9"}, //i=8
{10, 9, "Node10"},}; //i=9
以下是我用来对数组进行排序的逻辑:
for (int i = 0; i < table.length; i++) {
for (int j = i; j < table.length; j++) {
if (table[i][0] == table[j][1]) {
System.out.println(table[i][2].toString() + " is parent of " + table[j][2].toString());
}
}
}
这就是上面在控制台中显示的内容:
Root is parent of Node2
Root is parent of Node3
Root is parent of Node4
Root is parent of Node8
Root is parent of Node9
Node4 is parent of Node5
Node4 is parent of Node6
Node4 is parent of Node7
Node9 is parent of Node10
我正在努力创建TreeModel、HashTable、Object等,我可以用来创建JTree。
我已经被这个问题困扰了一个多星期,我现在真的可以借鉴别人的经验。
将数据组织到以下列中:
CREATE TABLE tree_node
(NodeID int,
ParentID int,
Value varchar(250)
...) //as many values per node as you want
这将允许您遍历记录集并填充JTree。
看看深度优先和广度优先的树遍历。
我是Java的新手,所以我不得不对这个问题进行一些研究。这项研究确实很耗时。我发现以下链接提供了从SQL数据创建JTree的最佳解决方案。
https://forums.oracle.com/forums/thread.jspa?threadID=2225475
这是我用来解决问题的代码
class myTree extends JPanel {
private DefaultMutableTreeNode rootNode;
private DefaultTreeModel treeModel;
public myTree() {
super(new GridLayout(1, 1)); //Set the layout for the panel that the jtree.
//The following object is a sample from a database and was used to validate
//the solution below. Make sure the table is properly sorted before you create the
//the object from the query.
Object[][] table = {
{1, null, "Root"}, //i=0
{2, 1, "Node2"}, //i=1
{3, 2, "Node3"}, //i=2
{4, 3, "Node4"}, //i=3
{5, 4, "Node5"}, //i=4
{6, 5, "Node6"}, //i=5
{7, 6, "Node7"}, //i=6
{8, 1, "Node8"}, //i=7
{9, 1, "Node9"}, //i=8
{10, 9, "Node10"},}; //i=9
//Create as many nodes as there are rows of data.
DefaultMutableTreeNode[] node = new DefaultMutableTreeNode[table.length];
for (int i = 0; i < table.length; i++) {
node[i] = new DefaultMutableTreeNode(table[i][2].toString());
}
rootNode = node[0]; //Set the root node
//Cycle through the table above and assign nodes to nodes
for (int i = 0; i < table.length; i++) {
for (int j = 1; j < table.length; j++) {
if (table[i][0] == table[j][1]) {
System.out.println(table[i][2].toString() + " is parent of " + table[j][2].toString());
node[i].add(node[j]);
}
}
}
//Creating the tree model. setting the root node.
treeModel = new DefaultTreeModel(rootNode);
//Setting the tree model to the JTree
JTree tree = new JTree(treeModel);
//adding the tree to the JPanel
add(tree);
}