我使用Swing控件创建了一个JTree
并命名为treeWorld
。它的根节点是根和儿童,即哺乳动物,鸟类,爬行动物,两栖动物,昆虫。现在我想以编程方式向Bird添加麻雀,杜鹃。
但是我不能给鸟类添加麻雀,杜鹃。
这是我的一段代码:
DefaultTreeModel model = (DefaultTreeModel)treeWorld.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
DefaultMutableTreeNode bird = new DefaultMutableTreeNode("Birds");
DefaultMutableTreeNode sparrow = new DefaultMutableTreeNode("sparrow");
DefaultMutableTreeNode cuckoo = new DefaultMutableTreeNode("cuckoo");
bird.add(sparrow);
bird.add(cuckoo);
this.pack();
this.setVisible(true);
答案 0 :(得分:2)
似乎问题是您永远不会将bird
节点添加到JTree
,请使用root.add(bird);
。
如果您的根节点已包含鸟节点,则需要在root
中搜索该节点,而不是创建新节点。
如果向可见树添加新节点,也可以使用model.nodesWereInserted(NODE, new int[]NODE.getChildCount()-1});
。 NODE
- 您添加新子项的节点。
示例:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class TestFrame extends JFrame {
private JTree t;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode bird = new DefaultMutableTreeNode("Birds");
root.add(bird);
DefaultTreeModel model = new DefaultTreeModel(root);
add(t=new JTree(model));
JButton btn = new JButton("add");
btn.addActionListener(getAddListener());
add(btn,BorderLayout.SOUTH);
}
private ActionListener getAddListener() {
return new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DefaultTreeModel model = (DefaultTreeModel)t.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
Enumeration children = root.children();
while(children.hasMoreElements()){
DefaultMutableTreeNode node = (DefaultMutableTreeNode) children.nextElement();
if(node.toString().equals("Birds")){
DefaultMutableTreeNode sparrow = new DefaultMutableTreeNode("sparrow");
DefaultMutableTreeNode cuckoo = new DefaultMutableTreeNode("cuckoo");
node.add(sparrow);
node.add(cuckoo);
model.nodesWereInserted(node, new int[]{node.getChildCount()-1,node.getChildCount()-2});
break;
}
}
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}
答案 1 :(得分:-1)
我不确定,因为您没有发布完整的可运行示例,但我认为,您只需要更新模型。
bird.add(sparrow);
bird.add(cuckoo);
model.reload(); // your model and tree don't know that you've added some nodes.
this.pack();
this.setVisible(true);