我有这张桌子:
+---------------------+
| Name | Type | Month |
+---------------------+
| John | xyz | March |
+---------------------+
| Joe | xyz | March |
+---------------------+
| Nick | abc | March |
+---------------------+
| Phil | abc | March |
+---------------------+
我想以这种方式在JTree上显示它的记录:
March
| xyz
| | John
| | Joe
| abc
| Nick
| Phil
我该怎么做?
我发现了很多关于此的文档,但我仍然无法理解如何从长度未知的数组中执行此操作。
我问这个是因为在UCanAccess中我选择了所有记录并将它们全部存储在一个数组中。
那么将这些节点添加到结构中的最有效方法是什么? (考虑到我要存储300多个元素)
答案 0 :(得分:1)
如果类型或月份更改,则循环数组并添加树节点。这是一个非常简单的例子。它使用描述数组的类Test2.java。确保您的数据排序正确:
public class Test2 {
private String month;
private String type;
private String name;
public Test2(String month, String type, String name) {
setMonth(month);
setType(type);
setName(name);
}
/**
* @return the month
*/
public String getMonth() {
return month;
}
/**
* @param month the month to set
*/
public void setMonth(String month) {
this.month = month;
}
/**
* @return the Type
*/
public String getType() {
return type;
}
/**
* @param Type the Type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
此类在JFrame中显示JTree:
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class Test1 extends JFrame {
public Test1() {
super("Test");
ArrayList<Test2> list = new ArrayList();
list.add(new Test2("March", "xyz", "John"));
list.add(new Test2("March", "xyz", "Joe"));
list.add(new Test2("March", "abc", "Nick"));
list.add(new Test2("March", "abc", "Phil"));
Iterator iter = list.iterator();
String prevMonth = "";
String prevType = "";
DefaultMutableTreeNode top = new DefaultMutableTreeNode("List");
DefaultMutableTreeNode month = null;
DefaultMutableTreeNode type = null;
while (iter.hasNext()) {
Test2 t = (Test2) iter.next();
if (!t.getMonth().equals(prevMonth)) {
if (month != null) {
top.add(month);
}
month = new DefaultMutableTreeNode(t.getMonth());
prevMonth = t.getMonth();
}
if (!t.getType().equals(prevType)) {
if (type != null) {
month.add(type);
}
type = new DefaultMutableTreeNode(t.getType());
prevType = t.getType();
}
type.add(new DefaultMutableTreeNode(t.getName()));
}
month.add(type);
top.add(month);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(new JScrollPane(new JTree(top)));
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String a[]) {
Test1 t1 = new Test1();
}
}