I am using mouse listener to know when a user clicks on nodes of a JTree. Although when the user clicks on the arrow for expansion of a node(view childs) the following exception is thrown:
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);
Any suggestions about how should I handle this case ? Should I simply try-catch inside the if statement? Also is this a good way to check for double-clicks or I should be doing it with a different method ? Thanks
Your listener tries to get the node at the mouse location. If there isn’t any node, null is returned by
tree.getPathForLocation(). Just test ifselPathis null before calling a method on it:And yes,
getClickCount()returns the number of clicks associated with the event, so it seems appropriate to check if it’s a double or a simple click.