MouseListener and JTree

I use a mouse listener to find out when a user clicks on JTree nodes. Although, when the user clicks on the arrow to expand the node (view child elements), 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 on how I should handle this case? Should I just try to catch an if statement inside? Is this also a good way to check for double clicks, or should I do it with another method? Thanks

+4
source share
2 answers

Your listener is trying to get the node at the location of the mouse. If node does not exist, null returns tree.getPathForLocation() . Just check if selPath is null before calling the method on it:

 if (selPath == null) { System.out.println("No node at this location"); } else { if (e.getClickCount() == 1) { ... } 

And yes, getClickCount() returns the number of clicks associated with the event, so it seems advisable to check if this is a double or simple click.

+6
source

I use a mouse listener to find out when a user clicks on JTree nodes.

Use TreeSelectionListener . TreeSelectionEvent contains very convenient methods for detecting nodes have been / selected.

See How to use trees for more details - answer the Node Choice .

0
source

Source: https://habr.com/ru/post/1388024/


All Articles