JTree的动态初始化

时间:2014-06-19 14:00:44

标签: java swing jtree treemodel

在谈到JTree时,我已经把头撞在砖墙上好几天了!

我想创建一个JTree,它在运行时从mp3标签动态获取其内容。到目前为止一切都那么好,除了我在填充JTree时头痛得厉害。经过大量的实验,我终于放弃了并寻求帮助。我一直在使用我在下面创建的类来试验将子节点添加到JTree中现有节点的方法。遇到的问题是在try块中,类型不兼容。我收到的错误是:

error: incompatible types: `TreeNode` cannot be converted to `MutableTreeNode`

treeModel.insertNodeInto第二个参数需要MutableTreeNode。我用来获取第二个参数rootNode.getChildAt()的父节点的方法返回TreeNode

还有这个???现在有人为getChildAt()返回TreeNode对象而不是DefaulMutableTreeNode,对象类型rootNode被初始化为???

package jtreeex;

import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

/**
 *
 * @author david
 */
public class JTreeEx implements Runnable
{

    public JTreeEx()
    {
        JFrame jfrm = new JFrame();  
        JPanel panel = new JPanel();
        JTree tree;

        DefaultMutableTreeNode rootNode;
        rootNode = new DefaultMutableTreeNode("Audio");
        DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
        treeModel.addTreeModelListener(new MyTreeModelListener());

        tree = new JTree(treeModel);
        tree.setEditable(true);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.setShowsRootHandles(true);
        String [] anArray = {"Dogs", "Cats"};


        // Inserts new root nodes from anArray
        for(int i = 0; i < anArray.length; i++)
        {
            treeModel.insertNodeInto(new DefaultMutableTreeNode(anArray[i]), 
                    rootNode, rootNode.getChildCount());

        }

        // Get enumeration of children of rootNode
        Enumeration eNum = rootNode.children();

        try
        {
            while(eNum.hasMoreElements() == true)
            {
                treeModel.insertNodeInto(new DefaultMutableTreeNode("Toby"), 
                        rootNode.getChildAt(1), rootNode.getChildCount());
            }
        }
        catch (Exception e)
        {
            System.out.println("no enums left");
        }

        panel.add(tree);

        jfrm.add(panel);
        jfrm.setSize(400,200);
        jfrm.setVisible(true);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        (new Thread(new JTreeEx())).start();
    }

    public void run()
    {

    }

}

1 个答案:

答案 0 :(得分:1)

  

treeModel.insertNodeInto需要MutableTreeNode作为其第二个参数。用于获取第二个参数的父节点的方法rootNode.getChildAt()返回TreeNode。

您正在构建树,并且您知道要将DefaultMutableTreeNodes插入树中,因此只需将TreeNode强制转换为DefaultMutableTreeNode:

treeModel.insertNodeInto(new DefaultMutableTreeNode("Toby"), 
    (DefaultMutableTreeNode)rootNode.getChildAt(1), rootNode.getChildCount());