我正在使用鼠标侦听器来了解用户何时单击JTree的节点。尽管当用户点击展开节点的箭头(View childs)时,会抛出以下异常:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Core.ChannelView$1.mousePressed(ChannelView.java:120)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:263)
at java.awt.Component.processMouseEvent(Component.java:6370)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)ChannelView listener:
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if (e.getClickCount() == 1) {
line 120>>>>> System.out.println(selPath.getLastPathComponent());
} else if (e.getClickCount() == 2) {
System.out.println("Double" +selPath.getLastPathComponent());
}
}
};
tree.addMouseListener(ml);关于我应该如何处理这个案例有什么建议吗?我是否应该简单地在if语句中使用try-catch?同样,这是一个检查双击的好方法,还是我应该用不同的方法来做?谢谢
发布于 2011-12-26 22:23:02
侦听器尝试获取鼠标位置处的节点。如果没有任何节点,tree.getPathForLocation()将返回null。只需测试selPath是否为空,然后再对其调用方法:
if (selPath == null) {
System.out.println("No node at this location");
}
else {
if (e.getClickCount() == 1) {
...
}是的,getClickCount()返回与事件相关的点击数,因此检查它是双击还是简单单击似乎是合适的。
发布于 2011-12-27 10:06:30
当用户点击JTree的节点时,我使用鼠标监听器来了解
。
请改用TreeSelectionListener。TreeSelectionEvent有一些非常方便的methods,用于发现选择了哪些节点。
有关更多详细信息,请参阅How to Use Trees - Responding to Node Selection。
https://stackoverflow.com/questions/8636540
复制相似问题