[英]Selection Path of a JTree
I've loaded a JTree with nodes from an XML Schema file using the XSOM API ( https://xsom.dev.java.net ). 我已经使用XSOM API( https://xsom.dev.java.net )从XML Schema文件中加载了带有节点的JTree。
Every time a file is selected I do the folowing: 每次选择文件时,我都会进行以下操作:
schemaParser = new XSDParser(selectedFile.getAbsolutePath());
TreeModel model = schemaParser.generateTreeModel();
schemaTree.setModel(model);
schemaTree.setCellRenderer(new SchemaTreeTraverser.SchemaTreeCellRenderer());
schemaTree is the variable name for the JTree. schemaTree是JTree的变量名称。
The code for XSDParser is as follows: 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;
}
}
Now whenever a node is selected in the JTree I do the following: 现在,无论何时在JTree中选择一个节点,我都将执行以下操作:
private void schemaTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {
TreePath path = schemaTree.getSelectionPath();
if(path != null)
System.out.println(path.toString());
}
However now no matter which node I select in the tree I get something like: [null, null, null, null] (depending on how far the hierarchy I go) 但是现在无论我在树中选择哪个节点,我都会得到类似的信息:[null,null,null,null](取决于我走的层次结构多远)
For a simple JTree this would usually print out the path to the node, eg: [JTree, colors, red] 对于简单的JTree,通常会打印出该节点的路径,例如:[JTree,颜色,红色]
Anyone any idea how to fix this? 有人知道如何解决这个问题吗?
Thanks, Patrick 谢谢,帕特里克
您不应该向JTree
询问选定的路径,而应该从TreeSelectionEvent
获取它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.