2010-12-03 97 views

回答

115
String[] items = {"A", "B", "C", "D"}; 
JList list = new JList(items); 

list.addMouseListener(new MouseAdapter() { 
    public void mouseClicked(MouseEvent evt) { 
     JList list = (JList)evt.getSource(); 
     if (evt.getClickCount() == 2) { 

      // Double-click detected 
      int index = list.locationToIndex(evt.getPoint()); 
     } else if (evt.getClickCount() == 3) { 

      // Triple-click detected 
      int index = list.locationToIndex(evt.getPoint()); 
     } 
    } 
}); 
+20

注意,如果列表中有足够的空间,并且用户双击空白空间,这将检测到列表中最后一个对象的双击。如果您只想检测包含项目的列表区域中的点击次数,可以这样检查: Rectangle r = list.getCellBounds(0,list.getLastVisibleIndex());如果(r!= null && r.contains(evt.getPoint())){int} index = list.locationToIndex(evt.getPoint()); } – 2012-03-01 23:14:26

10

我知道你有一个简单的解决方案,但你可能要为更广泛的解决方案,让您使用鼠标和关键局检查出List Action。正确的GUI设计应该允许使用这两种方法。

9

(基于穆罕默德Saligh,接受响应)

如果您使用的是NetBeans

选择的JList>活动窗口>的mouseClicked

private void jListNicknamesMouseClicked(java.awt.event.MouseEvent evt) {            
    JList list = (JList)evt.getSource(); 
    if (evt.getClickCount() == 2) { 
     int index = list.locationToIndex(evt.getPoint()); 
     System.out.println("index: "+index); 
    } 
}