当前位置: 代码迷 >> J2SE >> 为什么小弟我编写一个JTree的程序,实现点击添加树节点,但是小弟我的只能添加一次,不知为何?
  详细解决方案

为什么小弟我编写一个JTree的程序,实现点击添加树节点,但是小弟我的只能添加一次,不知为何?

热度:93   发布时间:2016-04-24 02:18:10.0
为什么我编写一个JTree的程序,实现点击添加树节点,但是我的只能添加一次,不知为何???
代码如下:
DefaultMutableTreeNode parentNode=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(parentNode==null){
return;
}
DefaultMutableTreeNode node=new DefaultMutableTreeNode(tfadd.getText());
TreePath selectPath=tree.getSelectionPath();
System.out.println(selectPath);

treeModel.insertNodeInto(node, parentNode, parentNode.getChildCount());
TreeNode[] nodes=treeModel.getPathToRoot(node);
TreePath path=new TreePath(nodes);
tree.scrollPathToVisible(path);
tree.setSelectionPath(path);
tree.startEditingAtPath(path);
tree.repaint();
// TreePath path=selectPath.pathByAddingChild(node);
// if(!tree.isVisible(path)){
// tree.makeVisible(path);
// }
// tree.clearSelection();
}
只粘贴了按钮事件的代码??
请求帮忙???

------解决方案--------------------
你把整个代码贴出来看看吧,这样也方便调试
------解决方案--------------------
给楼主一段代码做参考:
Java code
import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JTree;import javax.swing.tree.DefaultMutableTreeNode;import javax.swing.tree.DefaultTreeModel;public class TestJTree extends JFrame {    private JButton button ;    private JTree tree ;    private int treeNodeNum = 1 ;    DefaultMutableTreeNode _rootNode = new DefaultMutableTreeNode("root");    DefaultTreeModel _defaultTreeModel = new DefaultTreeModel(_rootNode);        public TestJTree(){        super();        this.setSize(300, 400);        button = new JButton("添加树节点");        button.addActionListener(new ActionListener(){            @Override            public void actionPerformed(ActionEvent e) {                DefaultMutableTreeNode _newNode = new DefaultMutableTreeNode("新添加的树节点_"+treeNodeNum);                _rootNode.add(_newNode);                _defaultTreeModel.reload();                treeNodeNum++;            }        });                tree = new JTree();                tree.setModel(_defaultTreeModel);                this.getContentPane().add(tree,BorderLayout.CENTER);        this.getContentPane().add(button,BorderLayout.SOUTH);    }            public static void main(String[] args){        TestJTree testJTree = new TestJTree();        testJTree.setVisible(true);    }    }