java - 如何在 java 中填充或重新加载 jtree

标签 java swing jtree

enter image description here

我在一个框架中有 2 个 JTrees,碰巧,例如,如果我选择蓝色(从左边的树),它将填充右边的树,之后,如果我现在选择红色,蓝色显示右侧不会消失以显示红色。

我尝试了三种不同的方法,比如 reloading()、repainting()、设置为 null,都没有用。

DefaultTreeModel defMod1 = (DefaultTreeModel)jTree1.getModel();                 
defMod1.reload();
jTree1.repaint();
defMod1.setRoot(null);

我想要的是右边的树显示左边树上当前选择的内容。即,如何重新加载或重绘右侧树以在左侧树上显示当前选择的内容?

我使用以下代码在我实现的 TreeSelectionListener 接口(interface)的 valueChange() 中获取当前选择。

DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();

我需要帮助。 谢谢

PS:我试过DevilsHnd的解决方案,但还是不行。部分代码如下。是的,我想要一种clearTree() 函数。

@Override
public void valueChanged(TreeSelectionEvent e){
    JTree treeSource = (JTree) e.getSource();
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();//gets the selection
    if(treeSource == jTree1 ){//if it is the tree on the left
        if(node == null)//if a node is selected
    return;
        Object nodeInfo = node.getUserObject();

        if(node.isLeaf()){
        try {
            String ipp = (String)nodeInfo;
            root2 = new DefaultMutableTreeNode(InetAddress.getByName((String)nodeInfo)+ " | " + "Local Disk (C:)");//root node for the tree on the right
            selectedPcIP = InetAddress.getByName(ipp).getHostAddress();
            selectedIP = "\\\\" + selectedPcIP +"\\c$";
            ArrayList creds = new BackItDb().getCreds();//gets user name and password from the database
            NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",creds.get(0).toString(),creds.get(1).toString());
            try {
                SmbFile file = new SmbFile("smb://"+selectedPcIP + "/" + System.getProperty("user.home").replace('C', 'c').replace(":", "$").replaceAll("[\\\\]","/")+"/",auth);//gets the folders from the selected PC

                jTree1.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));                              
                createSecondTree(file,root2,selectedPcIP);//This is a function that creates the tree on the right(jtree2).

                jTree1.setCursor(Cursor.getDefaultCursor());
                treeModel2 = new DefaultTreeModel(root2);// treemodel for the tree on the right
                jTree2.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
                jTree2.setModel(treeModel2);// the tree on the right
        }catch (UnknownHostException ex) {
            Logger.getLogger(BackIt_Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

最佳答案

当然我可能是错的,但听起来您想要的是某种类型的 clearTree() 方法,您可以在调用填充树的方法之前调用该方法。

这可以用这种类型的方法来完成:

/**
 * Removes all nodes from the supplied JTree except the Root.
 * 
 * @param tree (JTree) The JTree Variable Name for which to 
 * clear all nodes from.
 */
public static void clearTree(JTree tree) {
    if (tree.toString() == null) { return; }
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    root.removeAllChildren();
    model.reload();
}

EDIT: As per OP's question in comments: "How to remove all nodes including the root?"

要在这篇文章下方的评论中回答您的问题,它实际上是一个相当简单的一行:yourTree_VariableName.setModel(null);。所以,你可以像这样制作另一个简单的方法:

/**
 * This method will completely wipe out (clear) all nodes 
 * from a JTree including the Root node. After using this 
 * method you will need to construct another tree model to 
 * refill it.
 * 
 * @param tree (JTree) The JTree Variable Name for which to 
 * wipe all nodes from.
 */
public static void wipeTree(JTree tree) {
    tree.setModel(null);
}

关于java - 如何在 java 中填充或重新加载 jtree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45889945/

相关文章:

java - 在for循环中初始化变量

java - 使用 java.util.concurrent 触发并忘记

java - jButton 仅响应第二次单击

java - 使用正确的数字时,为什么我的组件无法正确居中?

java - 将不同的图标分配给 JTree 中的不同节点

java - 在 JTable 中添加或删除行后如何刷新 JTree

java - 我想在 mac 上安装 Java JDK 8,但 .bash_profile 无法检测到 JAVA_HOME

java - 带LinkedHashMap的多维字节数组……还有更好的办法吗?

java - JFrame 为空

java - 无法序列化 JTree 的根节点 (groovy/java)