如果用户按下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,events,swing
来源: https://codeday.me/bug/20191007/1865031.html