0

对 for 循环的语法有困难,它从数组中读取数据并将其添加到JTree.

public void init()
{   final String section1 = "JAVA";
    String[] sections = new String[]{ "Tutorial6", "Tutorial5", "Tutorial4", "Tutorial3", "Tutorial2", "Tutorial1" };

String contents[][] = {
        {"content1a", "content1b"},
        {"content2a", "content2b"},
        {"content3a", "content3b"}
    };  

    title = new DefaultMutableTreeNode(section1);

    for (int i=0; i<sections.length; i++)
    {   selection = new DefaultMutableTreeNode(( sections[i]));

        selection.insert(new DefaultMutableTreeNode((contents[i])),0);



        //title.insert(selection,0);
    }

添加这些部分可以正常工作,但是向这些部分添加节点是问题所在。如何让 for 循环工作,以便在解析 for 循环时将具有内容名称的节点添加到相关部分?

这是不起作用的代码:

    selection.insert(new DefaultMutableTreeNode((contents[i])),0);

谢谢 !!

4

1 回答 1

1

创建一个 TreeNode 实际上是一个单一的节点。因此,将数组传递给节点构造函数不会创建完整的节点列表。为了实现你想要的,添加一个嵌套的 for 循环。

String contents[][] =
{
    {"content1a", "content1b"},
    {"content2a", "content2b"},
    {"content3a", "content3b"}
};  

title = new DefaultMutableTreeNode(section1);

for (int i=0; i < sections.length; i++)
{
    selection = new DefaultMutableTreeNode(sections[i]);
    for (int k = 0; k < contents[i].length; ++k)
    {
        selection.add(new DefaultMutableTreeNode(contents[i][k]));
    }
    title.add(selection);
}
于 2013-07-20T18:51:35.127 回答