2011-12-26 7 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) 

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 문 안에서 간단히 시도해야합니까? 또한 이것은 더블 클릭을 확인하는 좋은 방법입니까 아니면 다른 방법으로 수행해야합니까? 감사합니다

답변

6

청취자는 마우스 위치에서 노드를 얻으려고합니다. 노드가 존재하지 않는 경우, null는 tree.getPathForLocation()에 의해 리턴됩니다.

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

을 그리고 네, getClickCount() 이벤트와 관련된 클릭 수를 반환, 그래서 더블 또는 간단한 클릭의 경우는 확인 적절한 것 같다 그냥 selPath가의 메소드를 호출하기 전에 null의 경우 테스트합니다.

0

사용자가 JTree의 노드를 클릭하는 시점을 알기 위해 마우스 수신기를 사용하고 있습니다.

대신 TreeSelectionListener을 사용하십시오. TreeSelectionEvent에는 어떤 노드가 선택 되었는가/발견 되었는가에 대한 매우 편리한 몇 가지가 있습니다 (methods).

자세한 내용은 How to Use Trees - Responding to Node Selection을 참조하십시오.

+0

청취자를 확인하고 구현했지만 더블 클릭을 확인하는 방법을 찾지 못했습니다. 가능한가요? – Giannis

+0

그 비트를 놓친 것, 미안. –