JTree For-Loop阵列语法

时间:2013-07-20 18:49:10

标签: java swing for-loop jtree

对于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);

谢谢!

1 个答案:

答案 0 :(得分: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);
}