【发布时间】:2013-07-19 17:27:51
【问题描述】:
我有一个简单的JTree,它系统地从相关变量中添加节点:
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);
}
我想要的是使用 For 循环,以避免额外的 selection.inserts
类似
String[] sections = new String[]{ "Tutorial1", "Tutorial2", "Tutorial3", "Tutorial4", "Tutorial5", "Tutorial6" };
for (int i=0; i < sections.length; i++) {
selection = new DefaultMutableTreeNode( sections[i] );
}
我该怎么做?
谢谢
【问题讨论】:
-
见Oracle tutorila How to use Tree有描述基本的东西
-
谢谢,我已经检查了这个问题之前的示例,并且知道节点是单独添加的
-
.. 我相信会有一种方法可以用几行代码添加所有节点,所以如果有人有想法,他们将不胜感激:)
-
好,相同的节点可以从循环中添加并在准备好的对象数组中迭代,没有区别,你的想法是正确的
-
不明白这个问题:只要你有数据要插入到一些数据结构中(任何集合都可以),只需迭代,创建节点并添加它们(注意:一旦你创建了模型,您必须使用 model api 添加节点,否则更改不会显示!)