我正在使用鼠标监听器来了解用户何时点击JTree的节点.虽然当用户单击箭头以扩展节点(查看子节点)时,会抛出以下异常:
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监听器:
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语句中尝试捕获吗?这也是检查双击的好方法,或者我应该使用不同的方法吗?谢谢
解决方法:
您的侦听器尝试将节点放在鼠标位置.如果没有任何节点,则tree.getPathForLocation()返回null.在调用方法之前,只测试selPath是否为null:
if (selPath == null) {
System.out.println("No node at this location");
}
else {
if (e.getClickCount() == 1) {
...
}
是的,getClickCount()返回与事件关联的点击次数,因此检查它是双击还是简单点击似乎是合适的.
标签:java,swing,jtree,mouselistener
来源: https://codeday.me/bug/20190530/1185057.html