JTree懒惰负载扩展

时间:2011-06-06 13:07:23

标签: java swing

希望你做得很好。

我有一个JTree,我使用数据库查询(每个节点)懒惰地加载。我在屏幕上有一个按钮,当用户单击按钮时,我在数据库中执行一些insert/update/delete,然后将模型添加回Jtree中仅使用root及其直接子项使用SQL(这会折叠树和选择和所有扩展节点崩溃,这是预期的,因为它是一个延迟加载的树)

我想要完成的是在用户点击按钮insert/update/delete之前,我读取所有展开的状态并将其保存在内存中然后当我重新初始化JTree我循环遍历这些扩展的子节点时调用jtree.expandPath但它不会扩展节点:(。

我甚至添加了TreeWillExpandListener并在treeWillExpand事件中添加了代码以从数据库中获取节点的子节点,我看到该查询确实已执行以获取childreen但JTree仍然显示为崩溃。

我真的需要你的帮助。请指教。这是代码段。

package marketdatagui;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.EventListenerList;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.io.File;
import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;


public class StressGroupModel
    implements TreeModel,Serializable, Cloneable
{
    protected EventListenerList listeners;

    private static final Object LEAF = new Serializable() { };

    private Map map;

    private NodeData root;

    private class NodeData{
        String id;
        String name;

        public String toString(){
            return name;
        }
    }

    public StressGroupModel()
    {
        this.root = new NodeData();
        root.id = "Root";
        root.name = "Root";

        this.listeners = new EventListenerList();

        this.map = new HashMap();

        List rootChildren = new ArrayList();

        NodeData d1 = new NodeData();
        d1.id = "5000007";
        d1.name = "Name5000007";

        rootChildren.add(d1);

        NodeData d2 = new NodeData();
        d2.id = "10000054";
        d2.name = "Name10000054";

        rootChildren.add(d2);
        map.put(root.id, rootChildren);
    }


    public Object getRoot()
    {
        return root;
    }

    public boolean isLeaf(Object node)
    {
        return map.get(node) == LEAF;
    }

    public int getChildCount(Object node)
    {
        List children = children(node);

        if (children == null)
            return 0;

        return children.size();
    }

    public Object getChild(Object parent, int index)
    {
        return children(parent).get(index);
    }

    public int getIndexOfChild(Object parent, Object child)
    {
        return children(parent).indexOf(child);
    }

    protected List children(Object node)
    {
        NodeData s = (NodeData)node;

        Object value = map.get(s.id);

        if (value == LEAF)
            return null;

        List children = (List)value;

        if (!"Root".equals(s.id))
        {
            String[][] dbData = getChildren(s.id);

            if (dbData != null)
            {
                children = new ArrayList(dbData.length);
                for (int i = 0; i < dbData.length; i++)
                {
                    NodeData d = new NodeData();
                    d.id = dbData[i][1];
                    d.name = dbData[i][1] + "Name";
                    children.add(d);
                    if ("R".equals(dbData[i][2]))
                        map.put(d, LEAF);
                }
            }
            else
                children = new ArrayList(0);

            map.put(s.id, children);       
        }

        return children;
    }

    private String[][] getChildren(String parent_uid){
        String sql = "select parent_uid,child_uid,child_type from stress_groups_mapping "
              + " where parent_uid="+ parent_uid
              +" order by parent_uid, child_uid";

        return Util.getTableData(sql);
    }

    public void valueForPathChanged(TreePath path, Object value)
    {
    }

    public void addTreeModelListener(TreeModelListener l)
    {
        listeners.add(TreeModelListener.class, l);
    }

    public void removeTreeModelListener(TreeModelListener l)
    {
        listeners.remove(TreeModelListener.class, l);
    }

    public Object clone()
    {
        try
        {
            StressGroupModel clone = (StressGroupModel)super.clone();

            clone.listeners = new EventListenerList();

            clone.map = new HashMap(map);

            return clone;
        }
        catch (CloneNotSupportedException e)
        {
            throw new InternalError();
        }
    }

}
  • 以下是我创建树的方法
  

public createTree {

JFrame f = new JFrame("Tree Dragging Tester");
          DefaultMutableTreeNode root = new DefaultMutableTreeNode(new Object());
          jtree = new JTree(new StressGroupModel());
          TreeWillExpandListener treeWillExpandListener = new TreeWillExpandListener() {
                public void treeWillCollapse(TreeExpansionEvent treeExpansionEvent)
                    throws ExpandVetoException {


                }

                public void treeWillExpand(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException {
                    TreePath path = treeExpansionEvent.getPath();
                    Object node =  path.getLastPathComponent();
                    ((StressGroupModel)jtree.getModel()).getChildCount(node);
                  }


          };

          jtree.addTreeWillExpandListener(treeWillExpandListener);

          f.getContentPane().add(jtree, BorderLayout.CENTER);
          f.setSize(300, 200);
          f.setVisible(true);
}
  • 以下是我保存展开状态的方法
  

Enumeration paths = jtree.getExpandedDescendants(new   的TreePath(jtree.getModel()getRoot()。));

  • 插入/更新/删除数据库内容
  • 现在重新初始化模型并添加回JTree(因此它选择最新的 来自DB的值
  • 现在我循环并调用expand以展开用户展开的节点 在他点击按钮之前,唉它仍然崩溃:(
  

jtree.setModel(new StressGroupModel());             while(paths.hasMoreElements()){

            TreePath treePath = (TreePath) paths.nextElement();

            try {

            jtree.expandPath(treePath);
            jtree.setSelectionPath(treePath);

            }
            catch(Exception ex){

            }

        }

1 个答案:

答案 0 :(得分:3)

我找到了解决方案。

在我的NodeData类中需要一个equals方法和hashCode,在我尝试扩展路径时设置新模型时内部出现问题,equals返回false,因为equals的默认实现是“浅比较”,即只比较引用,我必须覆盖hashCode和equals方法,并在equals方法中进行“深度比较”。

由于