Java Swing:JTree DefaultMutableTreeNode没有更新

时间:2015-06-24 09:15:50

标签: java swing jtree children treenode

我最近一直致力于Java Swing项目,今天我在修改DefaultMutableTreeNode的孩子时遇到困难。

以下SSCCE说明了问题:

import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

public class Test
{
    private static boolean executed = false;
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                //
                final DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
                final JTree tree = new JTree(root);
                tree.addMouseListener(new MouseAdapter()
                {
                    @Override
                    public void mousePressed(MouseEvent ev)
                    {
                        if (ev.getClickCount() == 2)
                        {
                            root.removeAllChildren();
                            for (String s: get())
                            {
                                root.add(new DefaultMutableTreeNode(s));
                                System.out.println(s + " added");
                            }
                            System.out.println();
                            tree.expandPath(tree.getSelectionPath());
                        }
                    }
                });
                frame.add(tree);
                frame.setSize(200,200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    static String[] get()
    {
        if (!executed)
        {
            executed = true;
            return new String[]{"a","b","c"};
        }
        else return new String[]{"a","b","c","d"};
    }
}

如您所见,第一次调用get()方法时,它返回一个3元素数组,之后返回一个4元素数组。当我第一次双击(实际按下)根节点时,应该有三个子节点(a,b和c),并且程序按预期运行。当我再次双击根节点时,我想它将有四个子节点。然而,它并没有。当您第二次双击时,仍然只有三个,而不是四个子节点。

我犯了错误吗?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您应该使用reload()方法

通知模型有关更改的信息

expand path之前添加此行,如下文

 DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
 model.reload(root); // notify changes to model 
 tree.expandPath(tree.getSelectionPath());