我正在使用 a来检测对项目的MouseListener
双击。JTree
那JTree
是位于一个JScrollPane
. 当我检测到双击 (a MouseEvent
) 时,我从JTree
. 大多数情况下,这工作正常。
现在,如果我双击带有子节点的(折叠)节点,该节点会展开,因此滚动窗格会向下滚动。当我尝试从单击位置获取树路径时,会JTree
查看当前(滚动)视图并返回错误的项目,因为单击位置指的是前一个视图(未滚动)。
有谁知道如何解决这个问题?下面,我将附上一个示例来演示该问题。
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
public class TestMain extends JDialog implements MouseListener {
protected final JTree tree;
public TestMain() {
tree = new JTree(getRootNode());
tree.addMouseListener(this);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(250, 300));
getContentPane().add(pane, BorderLayout.CENTER);
pack();
}
private TreeNode getRootNode() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
for (int i = 0; i < 10; i++) {
root.add(new DefaultMutableTreeNode("Node " + i));
}
DefaultMutableTreeNode sub = new DefaultMutableTreeNode("Sub");
root.add(sub);
for (int i = 0; i < 10; i++) {
sub.add(new DefaultMutableTreeNode("Sub " + i));
}
return root;
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (path != null) {
System.out.println(path.getLastPathComponent().toString());
}
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args) {
JDialog dialog = new TestMain();
dialog.setVisible(true);
}
}