📄 restorabletree.java
字号:
/**
* RestorableTree.java
*
* (C) Copyright Knowledge Media Institute 2000-2002
*
*
* Created: Mon Jan 14 16:12:41 2002
*
* $Id: RestorableTree.java,v 1.1 2007/05/01 10:51:31 chris Exp $
*/
package edu.ou.kmi.util;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
/**
* Tree with a restorable state.
*
* By "state" I mean expansion state of each node.
* State of the tree is saved calling method {@link #saveState()} and restored by {@link #restoreState()}.
* This class is abstract, user has to redefine method nodesAreEqual().
*
* @author "Matt Koss" <m.koss@open.ac.uk>
* @version 1.0
*/
public abstract class RestorableTree extends JTree {
Enumeration expandedNodes;
protected DefaultMutableTreeNode nodeRoot;
public RestorableTree( TreeModel model ) {
super( model );
nodeRoot = (DefaultMutableTreeNode) getModel().getRoot();
}
/**
* Saves the state of the tree.
*
*/
public void saveState() {
expandedNodes = getExpandedDescendants( new TreePath( nodeRoot ) );
}
/**
* Tries to restore a state of each node.
* If node does not exist, it is skipped.
*
*/
public void restoreState() {
if ( expandedNodes != null && nodeRoot.getChildCount() != 0 ) {
while ( expandedNodes.hasMoreElements() ) {
TreePath path = (TreePath) expandedNodes.nextElement();
Object[] o = path.getPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodeRoot.getFirstChild();
for ( int i = 1; i < o.length; i++ ) { // skip the first node
// go through all the nodes in the path and try to expand them
// find the relevant frame
while ( node != null ) {
if ( nodesAreEqual( (DefaultMutableTreeNode)o[i], node ) ) {
TreePath newPath = new TreePath( node.getPath() );
// expand found node, if it is not already
if ( ! isExpanded( newPath ) ) {
expandPath( newPath );
}
if ( node.getChildCount() != 0 ) {
node = (DefaultMutableTreeNode) node.getFirstChild();
} else {
node = null;
}
break;
} else {
node = (DefaultMutableTreeNode) node.getNextSibling();
}
}
}
}
}
}
/**
* Method for comparison of two nodes.
* Used for finding out whether we got to the node that was expanded before or not.
* This is one method that has to be redefined in the sub-class.
*
* @param node1 a <code>DefaultMutableTreeNode</code> value
* @param node2 a <code>DefaultMutableTreeNode</code> value
* @return a <code>boolean</code> value
*/
abstract protected boolean nodesAreEqual( DefaultMutableTreeNode node1, DefaultMutableTreeNode node2 );
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -