gpt4 book ai didi

Java检测鼠标长按

转载 作者:行者123 更新时间:2023-11-29 09:42:11 25 4
gpt4 key购买 nike

如果用户在 JList 组件上按下超过 3 秒,是否有任何方法可以捕获事件?

我发现困难的部分是事件需要在用户松开鼠标左键之前触发。 (这可以通过一对 mousePressed 和 mouseReleased 轻松完成)

最佳答案

这是我在类似情况下使用的方法:

public class Player implements Runnable, MouseListener
{
public void mousePressed(MouseEvent e)
{
holding = true;
thread = new Thread(this);
thread.start();
}

public void mouseReleased(MouseEvent e)
{
holding = false;
System.out.println("Held for: "+seconds);
}
public void mouseClicked(MouseEvent e){}

public void run()
{
try
{
while(holding)
{
seconds++;
// put some code here
if(seconds==3)
{
holding = false;
System.out.println("Held for maximum time!");
}
}
}catch(Exception e){e.printStackTrace();}

private boolean holding;
private int seconds;
private Thread thread;
}

通过调用 label.addMouseListener(new Player()); 将其添加到您的 JLabel;

关于Java检测鼠标长按,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6785385/

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