JTree - how to add nodes with a For-Loop?

老子叫甜甜 提交于 2019-12-20 06:30:10

问题


I have a simple JTree, that systematically adds nodes from relevant vars:

public void init()
{   
    final String section1 = "JAVA";

    final String section1_content1 = "Tutorial1";
    final String section1_content2 = "Tutorial2";
    final String section1_content3 = "Tutorial3";
    final String section1_content4 = "Tutorial4";
    final String section1_content5 = "Tutorial5";
    final String section1_content6 = "Tutorial6";

    final String content1a = "Introduction";
    final String content1b = "Hello World!";

    // Create the title node:
    title = new DefaultMutableTreeNode(section1);

    // Create and attach the 1st subtree:
    selection = new DefaultMutableTreeNode(section1_content1);

    selection.insert(new DefaultMutableTreeNode(content1a),0);
    selection.insert(new DefaultMutableTreeNode(content1b),0);

    title.insert(selection,0);
}

what I would like, is to use a For-Loop, to avoid extra selection.inserts

something like

String[] sections = new String[]{ "Tutorial1", "Tutorial2", "Tutorial3", "Tutorial4", "Tutorial5", "Tutorial6" };

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

How would I do this?

thanks


回答1:


You could put all of the values into an enum and iterate through that instead.

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html




回答2:


The solution is very simple:

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

sections[i] needs double brackets



来源:https://stackoverflow.com/questions/17752099/jtree-how-to-add-nodes-with-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!