2011-12-26 45 views
4

我使用鼠標偵聽器來了解用戶何時單擊JTree的節點。當用戶點擊一個節點的擴展箭頭儘管(查看孩子的)以下異常被拋出:MouseListener和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) 

峽聽衆:

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語句裏面試一下?此外,這是一個檢查雙擊的好方法,或者我應該用不同的方法來做到這一點?謝謝

回答

6

您的監聽器試圖獲取鼠標位置的節點。如果沒有任何節點,則返回空值tree.getPathForLocation()。只是測試,如果selPath是調用一個方法就可以了之前空:

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

是的,getClickCount()返回與該事件相關的點擊數,因此,如果它是一個雙或簡單的點擊似乎是適當的檢查。