0
修复了上一篇文章。循环给出错误并从ArrayList向JTree添加错误值
除了if语句之外,一切似乎都运行良好,它有时会将错误的数字添加到错误的地方,并且会给出错误。
目标是将两个ArrayLists添加到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();
}
});
}
}
谢谢!这似乎已修复了错误。它似乎仍然将一些arraylist2添加到错误的地方。例如1.1将成为1的孩子,但然后1.2成为2的孩子。任何想法? – Keags