我现在正在学习java,我的一个应用程序是简单的Swing文件层次结构查看器,它使用JTree小部件。我的问题是,当我以这种方式实现TreeModel时(例如《Nutshell中的Java基础类》一书中的例子),我如何添加Jtree鼠标选择事件监听器(例如将节点文本值记录到控制台):
public class FileTreeDemo {
public static void main(String[] args) {
File root;
if (args.length > 0)
root = new File(args[0]);
else
root = new File(System.getProperty("user.home"));
FileTreeModel model = new FileTreeModel(root);
MyJtree tree = new MyJtree();
tree.setModel(model);
JScrollPane scrollpane = new JScrollPane(tree);
JFrame frame = new JFrame("FileTreeDemo");
frame.getContentPane().add(scrollpane, "Center");
frame.setSize(400, 600);
frame.setVisible(true);
}
}
class FileTreeModel implements TreeModel {
protected File root;
public FileTreeModel(File root) {
this.root = root;
}
public Object getRoot() {
return root;
}
public boolean isLeaf(Object node) {
return ((File) node).isFile();
}
public int getChildCount(Object parent) {
String[] children = ((File) parent).list();
if (children == null)
return 0;
return children.length;
}
public Object getChild(Object parent, int index) {
String[] children = ((File) parent).list();
if ((children == null) || (index >= children.length))
return null;
return new File((File) parent, children[index]);
}
public int getIndexOfChild(Object parent, Object child) {
String[] children = ((File) parent).list();
if (children == null)
return -1;
String childname = ((File) child).getName();
for (int i = 0; i < children.length; i++) {
if (childname.equals(children[i]))
return i;
}
return -1;
}
public void valueForPathChanged(TreePath path, Object newvalue) {
}
public void addTreeModelListener(TreeModelListener l) {
}
public void removeTreeModelListener(TreeModelListener l) {
}
}
在这里,我试图通过MyJtree扩展JTree类,并添加AddTreeSelectionListener
public class MyJtree extends JTree {
public MyJtree() {
super();
this.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e
.getPath().getLastPathComponent();
System.out.println("You selected " + node);
}
});
}
}
但后来我点击JTree项目,我得到了这个:
线程"AWT-EventQueue-0"java.lang.ClassCastException中出现异常:java.io.File不能强制转换为javax.swing.tree.DefaultMutableTreeNode
那么,我该怎么解决呢?
在侦听器中不强制转换为DefaultMutableTreeNode
。getLastPathComponent
方法从TreeModel
返回一个元素,在您的情况下,它是File
堆栈跟踪和异常消息在这个上非常清楚
由于您的模型包含File对象,e.getPath().getLastPathComponent()返回File对象(只是您的模型返回的对象)。此外,为了避免ClassCastException,您可能需要检查返回的Object是否正是您所期望的类。
Object object = e.getPath().getLastPathComponent();
if (object instanceof File){
File file = (File) object;
}