Reputation: 31086
In my Java Swing app, I have a JList, and when I double click on an item in the list, it always does click count == 1 things first then do things in click count == 2, why ?
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");
}
}
});
No matter how fast I click, I intentionally put "if (e.getClickCount()==2)" before "else if (e.getClickCount()==1)", it still catches ClickCount==1 first ? Why ? How to fix it ?
Upvotes: 3
Views: 1777
Reputation: 31086
OK, after some Goggling and my own enhancement, here is the code that works to my original expectations :
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);
Upvotes: 2