我已经使用 XSOM API ( https://xsom.dev.java.net )从 XML Schema 文件中加载了带有节点的 JTree 。
每次选择文件时,我都会执行以下操作:
schemaParser = new XSDParser(selectedFile.getAbsolutePath());
TreeModel model = schemaParser.generateTreeModel();
schemaTree.setModel(model);
schemaTree.setCellRenderer(new SchemaTreeTraverser.SchemaTreeCellRenderer());
schemaTree 是 JTree 的变量名。
XSDParser 的代码如下:
package schemaparser;
import java.io.*;
import com.sun.xml.xsom.XSSchemaSet;
import com.sun.xml.xsom.impl.util.SchemaTreeTraverser;
import com.sun.xml.xsom.impl.util.SchemaWriter;
import com.sun.xml.xsom.parser.XSOMParser;
import javax.swing.tree.TreeModel;
public class XSDParser {
private XSOMParser reader;
private XSSchemaSet xss;
public XSDParser(String parseFile){
try {
reader = new XSOMParser();
reader.parse(new File(parseFile));
xss = reader.getResult();
if (xss == null) {
System.out.println("error");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public TreeModel generateTreeModel() {
SchemaTreeTraverser stt = new SchemaTreeTraverser();
stt.visit(xss);
TreeModel model = stt.getModel();
System.out.println("Returning the tree model");
return model;
}
}
现在,每当在 JTree 中选择一个节点时,我都会执行以下操作:
private void schemaTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {
TreePath path = schemaTree.getSelectionPath();
if(path != null)
System.out.println(path.toString());
}
但是现在无论我在树中选择哪个节点,我都会得到类似: [null, null, null, null] (取决于我走多远的层次结构)
对于一个简单的 JTree,这通常会打印出节点的路径,例如:[JTree, colors, red]
有人知道如何解决这个问题吗?
谢谢,帕特里克