【发布时间】:2016-07-03 03:35:50
【问题描述】:
修复了之前的帖子。
除了 if 语句之外,一切似乎都运行良好,它有时会在错误的位置添加错误的数字并给出错误。
目的是将两个 ArrayList 添加到 Jtree 中。 Arraylist 包含整数,如 (1,2,3,4 等),第二个包含双数,如 (1.1,1.2,2.1 等)。
我想将第一个数组添加到 JTree,我已经设法做到了。但是我想添加第二个数组列表,这样它就是第一个的孩子。
因此 1.1 和 1.2 是 1 的子代,而 2.1 是 2 的子代,依此类推。
任何帮助将不胜感激。
代码是可运行的。
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
public class TreeExample2 extends JFrame
{
private JTree tree;
public TreeExample2()
{
final ArrayList<String> arrayList = new ArrayList<String>();
final ArrayList<String> arrayList2 = new ArrayList<String>();
JPanel frameG1= new JPanel();
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList2.add("1.1");
arrayList2.add("1.2");
arrayList2.add("2.1");
arrayList2.add("4.1");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JTree Example");
this.pack();
frameG1.setVisible(true);
frameG1.setSize(500,500);
frameG1.setLayout(null);
JFrame frameG2 = new JFrame("Cell Tree");
frameG2.setSize( 400, 900 );
frameG2.setVisible(true);
frameG2.setBackground( Color.gray );
DefaultMutableTreeNode root = new DefaultMutableTreeNode("cells");
tree = new JTree(root);
frameG2.add(tree);
int i=0;
//should through first array list and adds it to root
for (int n =0; n<arrayList.size();) {
DefaultMutableTreeNode cells = new DefaultMutableTreeNode(arrayList.get(n));
root.add(cells);
//should go through jtree elements
Enumeration search = root.postorderEnumeration();
while(search.hasMoreElements()){
//should compare each element to a 2nd array
//2nd array consists of double numbers like 1.1,1.2,2.1 etc
//so i split it before the "." so 1.1 is 1
//first array consists of whole numbers like 1, 2, 3
//want to make 1.1 child of 1 etc.
if (search.nextElement().toString().equals(arrayList2.get(i).toString().split("\\.", 2)[0])) {
DefaultMutableTreeNode NewCells = new DefaultMutableTreeNode(arrayList2.get(i));
cells.add(NewCells);
i++;
}
}
n++;
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TreeExample2();
}
});
}
}
【问题讨论】:
标签: java loops if-statement arraylist jtree