home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Programming Languages Suite
/
ProgLangD.iso
/
VCAFE.3.0A
/
Main.bin
/
StringTreeModel.java
< prev
next >
Wrap
Text File
|
1998-09-27
|
3KB
|
132 lines
package com.symantec.itools.swing.models;
import com.sun.java.swing.tree.*;
import com.sun.java.swing.tree.DefaultMutableTreeNode;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Stack;
public class StringTreeModel
extends com.sun.java.swing.tree.DefaultTreeModel
{
public StringTreeModel()
{
super(new DefaultMutableTreeNode("root"));
}
//
// Properties
//
public void setItems(String[] items)
{
((DefaultMutableTreeNode)getRoot()).removeAllChildren();
int indent = 0;
int lastIndent = 0;
Vector parents = new Vector();
parents.addElement(getRoot());
DefaultMutableTreeNode newNode = null;
for (int i = 0; i < items.length ;i++)
{
String newItem = items[i];
indent = 0;
while(Character.isWhitespace(newItem.charAt(indent)))
indent++;
if (indent - lastIndent < 2)
{
newNode = new DefaultMutableTreeNode(newItem.trim());
((DefaultMutableTreeNode)parents.elementAt(indent)).add(newNode);
if (parents.size() < indent +2)
parents.setSize(parents.size()+1);
parents.setElementAt(newNode,indent+1);
lastIndent = indent;
}
else
{
System.err.println("illegal tree node: "+newItem+" - check indentation");
nodeStructureChanged((TreeNode)getRoot());
break;
}
}
nodeStructureChanged((TreeNode)getRoot());
}
public String[] getItems()
{
Vector itemsVector = new Vector();
PreorderEnumeration enum = new PreorderEnumeration((TreeNode)getRoot());
enum.nextElement(); // skip root
while(enum.hasMoreElements())
{
DefaultMutableTreeNode nextNode = (DefaultMutableTreeNode)enum.nextElement();
StringBuffer nextString = new StringBuffer(nextNode.toString());
for(int i = 1; i < nextNode.getLevel(); i++)
nextString.insert(0," ");
itemsVector.addElement(nextString.toString());
}
String items[] = new String[itemsVector.size()];
itemsVector.copyInto(items);
return items;
}
public void setRootName(String rootName)
{
((DefaultMutableTreeNode)getRoot()).setUserObject(rootName);
reload();
}
public String getRootName()
{
String rootName = (String)(((DefaultMutableTreeNode)getRoot()).getUserObject());
if (rootName != null)
return rootName;
else
return "root";
}
//
// Implementation
//
// from DefaultMutableTreeNode...
final class PreorderEnumeration
implements Enumeration
{
protected Stack stack;
public PreorderEnumeration(TreeNode rootNode)
{
super();
Vector v = new Vector(1);
v.addElement(rootNode); // PENDING: don't really need a vector
stack = new Stack();
stack.push(v.elements());
}
public boolean hasMoreElements()
{
return (!stack.empty() && ((Enumeration)stack.peek()).hasMoreElements());
}
public Object nextElement()
{
Enumeration enumer = (Enumeration)stack.peek();
TreeNode node = (TreeNode)enumer.nextElement();
Enumeration children = node.children();
if (!enumer.hasMoreElements())
stack.pop();
if (children.hasMoreElements())
stack.push(children);
return node;
}
}
}