为什么我不能在Java中首先获得鼠标点击次数== 2?

时间:2015-03-11 21:58:02

标签: java swing jlist click-counting

在我的Java Swing应用程序中,我有一个JList,当我双击列表中的一个项目时,它总是先点击计数== 1个事情然后点击计数== 2,为什么?

 list.addMouseListener(new MouseAdapter()
 {
   public void mouseClicked(MouseEvent e)
   {
     if (SwingUtilities.isLeftMouseButton(e))
     {
       if (e.getClickCount()==1) Out("Left-ClickCount()==1");
       else if (e.getClickCount()==2) Out("Left-ClickCount()==2");     
     }
     else if (SwingUtilities.isRightMouseButton(e))
     {
       if (e.getClickCount()==2) Out("Right-ClickCount()==2");
       else if (e.getClickCount()==1) Out("Right-ClickCount()==1");
     }
   }
 });

无论我点击多快,我都故意把#34; if(e.getClickCount()== 2)"之前"否则if(e.getClickCount()== 1)",它仍然首先捕获ClickCount == 1?为什么?如何解决?

1 个答案:

答案 0 :(得分:1)

好的,在一些Goggling和我自己的增强功能之后,这里的代码符合我最初的期望:

  boolean isAlreadyOneClick=false;
...
    DefaultListModel xlistModel=new DefaultListModel();
    JList xlist=new JList(xlistModel);
    xlist.addMouseListener(new MouseAdapter()
    {
      public void mouseClicked(MouseEvent e)
      {
        int index=xlist.locationToIndex(e.getPoint());
        String item=xlistModel.getElementAt(index).toString();

        if (SwingUtilities.isLeftMouseButton(e))
        {
          if (isAlreadyOneClick)
          {
            System.out.println("Left double click : "+item);
            isAlreadyOneClick=false;
          }
          else
          {
            isAlreadyOneClick=true;
            Timer t=new Timer("doubleclickTimer",false);
            t.schedule(new TimerTask()
            {
              @Override
              public void run()
              {
                if (isAlreadyOneClick) System.out.println("Left single click : "+item);
                isAlreadyOneClick=false;
              }
            },250);
          }              
        }
        else if (SwingUtilities.isRightMouseButton(e))
        {
          if (isAlreadyOneClick)
          {
            System.out.println("Right double click : "+item);
            isAlreadyOneClick=false;
          }
          else
          {
            isAlreadyOneClick=true;
            Timer t=new Timer("doubleclickTimer",false);
            t.schedule(new TimerTask()
            {
              @Override
              public void run()
              {
                if (isAlreadyOneClick) System.out.println("Right single click : "+item);
                isAlreadyOneClick=false;
              }
            },250);
          }
        }
      }
    });

    xlistModel.addElement("123");
    xlistModel.addElement("abc");
    JFrame f=new JFrame("Test Clicks");
    f.add(xlist);
    f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { } });
    f.setBackground(SystemColor.control);

    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);