我有一个应用程序,其中包含一个支持DefaultTreeModel的JTree,它用于显示反映我服务器上文件系统一部分的文件层次结构(我将此称为我的客户端应用程序)。我还有一个服务器应用程序,它提供我的客户端应用程序需要显示的数据(我将此称为我的服务器应用程序)。我正在使用“懒惰加载子”方法,以便我只需要将文件加载到我的树中,如果用户对它们感兴趣的话。延迟加载方法:
treeWillExpand(TreeExpansionEvent evt)
DefaultTreeModel.insertNodeInto()
。DefaultTreeModel.nodeStructureChanged()
。以上工作正常,懒惰加载孩子我没有任何问题。我的问题出现在新数据上传到服务器并且我想更新树不仅包括新数据,而且还要将扩展状态和选定节点设置为更新树之前的状态(以便用户因为有新的数据需要查看,所以不会在树上蠢蠢欲动。流程如下:
JTree.getExpandedDescendants()
JTree.getSelectionPath()
JTree.getExpandedDescendants()
调用JTree.expandPath()
返回的树路径枚举。我的问题是,无论我尝试什么,树的GUI都不会更新以反映扩展状态。我知道我对expandPath的调用正在发挥作用,因为我可以看到客户端发送的数据请求以及每次调用expandPath时来自服务器的数据的响应。我还在另一个窗口中显示有关当前所选节点的信息,并显示正确选择的节点。但是,令我失望的是,GUI只显示根节点(已展开)和它的子节点(未展开),而不是之前的展开状态。
所以我的问题是:如何恢复JTree的扩展状态,以便在数据模型更新之前和之后GUI保持不变?
这些是我尝试的一些事情:
equals()
和hashCode()
来解决,但这对我不起作用。setExpandsSelectedPaths(true)
,nodeStructureChanged()
,JTree.invalidate()
这是我的SSCCE:
package tree.sscce;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.JButton;
import java.util.Enumeration;
import javax.swing.BoxLayout;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
public class TreeSSCCE extends JFrame implements TreeWillExpandListener {
private static final long serialVersionUID = -1930472429779070045L;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TreeSSCCE inst = new TreeSSCCE();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
inst.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
});
}
private DefaultMutableTreeNode rootNode;
private JTree tree;
private DefaultTreeModel treeModel;
private TreePath selectionPathPriorToNewData;
private Enumeration<TreePath> expandedPathsPriorToNewData;
private int treeSize = 5;
public TreeSSCCE() {
this.setBounds(0, 0, 500, 400);
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel, BorderLayout.CENTER);
mainPanel.setBounds(0, 0, 500, 400);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel descriptionPanel = new JPanel();
descriptionPanel.setBounds(0, 0, 500, 200);
mainPanel.add(descriptionPanel);
JTextPane textPane = new JTextPane();
String newLine = System.getProperty("line.separator");
descriptionPanel.setLayout(new BorderLayout(0, 0));
textPane.setText("Start by expanding some nodes then click 'Add New Data' and you will notice that the tree state is not retained.");
descriptionPanel.add(textPane);
// Initialize The Tree
tree = new JTree();
rootNode = new DefaultMutableTreeNode("Root");
treeModel = new DefaultTreeModel(rootNode);
tree.addTreeWillExpandListener(this);
tree.setModel(treeModel);
tree.setShowsRootHandles(true);
populateTree(false);
JScrollPane scrollPane = new JScrollPane(tree);
mainPanel.add(scrollPane);
JPanel buttonPanel = new JPanel();
mainPanel.add(buttonPanel);
JButton btnAddNewData = new JButton("Add New Data");
btnAddNewData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
addNewDataToTree();
}
});
buttonPanel.add(btnAddNewData);
}
private void removeAllTreeNodes()
{
while(!treeModel.isLeaf(treeModel.getRoot()))
{
treeModel.removeNodeFromParent((MutableTreeNode)treeModel.getChild(treeModel.getRoot(),0));
}
treeModel = null;
treeModel = new DefaultTreeModel(rootNode);
tree.setModel(treeModel);
}
public void restoreExpansionState(Enumeration enumeration)
{
if (enumeration != null)
{
while (enumeration.hasMoreElements())
{
TreePath treePath = (TreePath) enumeration.nextElement();
tree.expandPath(treePath);
tree.setSelectionPath(treePath);
}
tree.setSelectionPath(selectionPathPriorToNewData);
}
}
protected void addNewDataToTree()
{
// save the tree state
selectionPathPriorToNewData = tree.getSelectionPath();
expandedPathsPriorToNewData = tree.getExpandedDescendants(new TreePath(tree.getModel().getRoot()));
removeAllTreeNodes();
populateTree(true);
restoreExpansionState(expandedPathsPriorToNewData);
}
private void populateTree(boolean newData)
{
if(newData)
treeSize++;
MyParentNode[] parents = new MyParentNode[treeSize];
for(int i = 0; i < treeSize; i++)
{
parents[i] = new MyParentNode("Parent [" + i + "]");
treeModel.insertNodeInto(parents[i], rootNode, i);
}
}
@Override
public void treeWillCollapse(TreeExpansionEvent evt) throws ExpandVetoException {
// Not used.
}
@Override
public void treeWillExpand(TreeExpansionEvent evt) throws ExpandVetoException
{
System.out.println("Tree expanding: " + evt.getPath());
tree.setExpandsSelectedPaths(true);
tree.setSelectionPath(evt.getPath());
// we have already loaded the top-level items below root when we
// connected so lets just return...
if(evt.getPath().getLastPathComponent().equals(treeModel.getRoot()))
return;
// if this is not root lets figure out what we need to do.
DefaultMutableTreeNode expandingNode = (DefaultMutableTreeNode) evt.getPath().getLastPathComponent();
// if this node already has children then we don't want to reload so lets return;
if(expandingNode.getChildCount() > 0)
return;
// if this node has no children then lets add some
MyParentNode mpn = new MyParentNode("Parent Under " + expandingNode.toString());
treeModel.insertNodeInto(mpn, expandingNode, expandingNode.getChildCount());
for(int i = 0; i < 3; i++)
{
treeModel.insertNodeInto(new DefaultMutableTreeNode("Node [" + i + "]"), mpn, i);
}
}
private class MyParentNode extends DefaultMutableTreeNode
{
private static final long serialVersionUID = 433317389888990065L;
private String name = "";
public MyParentNode(String _name)
{
super(_name);
name = _name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyParentNode other = (MyParentNode) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public boolean isLeaf()
{
return false;
}
private TreeSSCCE getOuterType() {
return TreeSSCCE.this;
}
}
}
提前感谢您提供的任何帮助。
P.S。这是我的第一个问题,所以如果我正确地问我,请告诉我(并在我身上轻松一下;))。
答案 0 :(得分:1)
我正在使用自定义树模型(扩展DefaultTreeModel)并在DBTreeEvent.STRUCTURE_CHANGED事件中做出反应来处理此问题。这就是我为保护旧状态所做的工作。不确定它是否会对你有所帮助..
//NOTE: node is the tree node that caused the tree event
TreePath nodesPath = new TreePath(node.getPath());
TreePath currentSel = myTree.getLeadSelectionPath();
List<TreePath> currOpen = getCurrExpandedPaths(nodesPath);
super.nodeStructureChanged(node);
reExpandPaths(currOpen);
myTree.setSelectionPath(currentSel);
private List<TreePath> getCurrExpandedPaths(TreePath currPath)
{
List<TreePath> paths = new ArrayList<TreePath>();
Enumeration<TreePath> expandEnum = myTree.getExpandedDescendants(currPath);
if (expandEnum == null)
return null;
while (expandEnum.hasMoreElements())
paths.add(expandEnum.nextElement());
return paths;
}
private void reExpandPaths(List<TreePath> expPaths)
{
if(expPaths == null)
return;
for(TreePath tp : expPaths)
myTree.expandPath(tp);
}