删除节点后 JTree 不更新

JTree doesn`t update after removing node

我正在尝试从 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));

我的 class 树如下

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; 然后把它放在老树上就可以了

我该如何解决这个问题以及为什么这不起作用?谢谢

When I replace all that with SwingUtilites.invokeLater(), it worked. I don't understand why.

按照建议, be sure to construct and manipulate Swing GUI objects only on the event dispatch thread‌ 。特别是,从另一个线程更新 TreeModel 意味着监听 JTree 视图可能会以某种意想不到的顺序接收更新——或者根本不接收更新。