gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:07:14 25 4
gpt4 key购买 nike

在我的 Java Swing 应用程序中,我有一个 JList,当我双击列表中的一个项目时,它总是先执行 click count == 1 的操作,然后再执行 click count == 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");
}
}
});

不管我点击多快,我故意把"if (e.getClickCount()==2)"放在"else if (e.getClickCount()==1)"之前,它仍然先捕捉到ClickCount==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);

关于java - 为什么我不能首先在 Java 中获得鼠标点击计数 == 2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28998192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com