关于JTree树的鼠标点击事件
JTree中如何获得我点击的每个节点的值,也就是说在我点击这棵树的任意一个结点时,怎样才能确定我当前正在点击的是哪一个结点。
------解决方案-------------------- public java.lang.Object getLastSelectedPathComponent();
public javax.swing.tree.TreePath getSelectionPath();
和其他
------解决方案--------------------类似这样:
class MyTree extends JTree
覆盖方法:
protected void fireValueChanged(TreeSelectionEvent e)
获取节点内容:
DefaultMutableTreeNode node = (DefaultMutableTreeNode) (this.getLastSelectedPathComponent());
Object obj = node.getUserObject();
if (obj instanceof Project) {
Project project = (Project)obj;
} else if (obj instanceof Server) {
Server tmpServer = (Server) obj;
} else {
}
------解决方案--------------------
Java code
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent evt) {
// Get all nodes whose selection status has changed
TreePath[] paths = evt.getPaths();
// Iterate through all affected nodes
for (int i=0; i<paths.length; i++) {
if (evt.isAddedPath(i)) {
// This node has been selected
} else {
// This node has been deselected
}
}
}
});