删除节点

时间:2016-06-23 12:00:44

标签: java eclipse swing jtree

我正在尝试从JTree中删除节点,我有两个代码 那段代码正在运作

public class test {
private JFrame frame;
JTree tree;
DefaultMutableTreeNode root;
DefaultTreeModel model;
private Map<String, DefaultMutableTreeNode> treeMap;

public static void main(String[] args) {
    test t = new test();
    //scrolltree is basically a panel contains class has JTree
    scrolltree st = new scrolltree();
    t.frame.add(st);
    JButton b = new JButton("remove node");
    t.frame.add(b, BorderLayout.SOUTH);
    b.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            DefaultTreeModel model = (DefaultTreeModel) st.getTree().getTree().getModel();
            String key = new currentfolder().getCurrentfolder() + "/" + "a3.png";
            System.out.println(key);
            model.removeNodeFromParent(st.getTree().getTreeMap().get(key));
        }
    });
    t.frame.revalidate();
    t.frame.repaint();

}

public test() {
    frame = new JFrame();
    frame.setVisible(true);
    frame.setSize(500, 500);
}

并且该代码将其完美删除并更新

而另一个删除节点但不更新它(除非我创建了新树并用旧树替换)

我已经尝试了所有列出的解决方案,例如https://community.oracle.com/thread/2495518?tstart=0

但他们没有工作 我的非工作代码如下:

     DefaultTreeModel model = (DefaultTreeModel)startframe.getScrolltree().getTree().getTree().getModel();
     String key = new currentfolder().getCurrentfolder()+"/"+"a3.png";
     System.out.println(key);
     model.removeNodeFromParent(startframe.getScrolltree().getTree().getTreeMap().get(key));

我的班级树如下

public class tree {
JTree tree;
DefaultMutableTreeNode node1;
DefaultTreeModel model;
String name = new currentfolder().getInitial();// path to directory that its
                                                // content appear in tree
private Map<String, DefaultMutableTreeNode> treeMap;

public tree() {
    tree = new JTree();
    tree.setExpandsSelectedPaths(true);
    node1 = new DefaultMutableTreeNode(name);
    model = new DefaultTreeModel(node1);
    tree.setModel(model);
    treeMap = new HashMap<>();
    treeMap.put(name, node1);
    //method to inset many other nodes
    import_data(new File(name), node1);

    model.reload();
    tree.setOpaque(false);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setBorder(javax.swing.BorderFactory.createCompoundBorder(
            new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED),
            javax.swing.BorderFactory.createTitledBorder("")));
    tree.setVisible(true);

当我做tree t = new tree;时 然后把它放在它工作的老树上

我该如何解决这个以及任何解释为何这不起作用?感谢

1 个答案:

答案 0 :(得分:3)

  

当我用SwingUtilites.invokeLater()替换所有内容时,它有效。我不明白为什么。

根据建议here,请确保仅在event dispatch thread‌上构造和操作Swing GUI对象。特别是,从另一个线程更新TreeModel意味着监听JTree视图可能会以某种意外顺序接收更新 - 或者根本不接收。