如何让Java每秒都添加一个私有int mouseClick?

时间:2014-11-03 01:40:51

标签: java jgrasp

public class Blank extends WindowController
{
    private int mouseClicks;

    public void onMousePress(Location point)
    {
         mouseClicks++;
    }
}

我的目标是让mouseClicks每秒递增一次,而只需点击一次即可启动它。

3 个答案:

答案 0 :(得分:1)

这是我能得到的最佳解决方案。

public class Blank extends WindowController
{
    private final AtomicInteger mouseClicks = new AtomicInteger();
    private boolean hasStarted = false;

    public void onMousePress(Location point)
    {
       if(!hasStarted){
         hasStarted = true;
         Thread t = new Thread(){
             public void run(){
                 while(true){
                     mouseClicks.incrementAndGet(); //adds one to integer
                     Thread.sleep(1000); //surround with try and catch
                 }
             }
         };
         t.start();
      }
    }
}

答案 1 :(得分:0)

使用Thread.sleep(1000);暂停执行一秒钟。

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

答案 2 :(得分:-1)

您可以测试自上次点击以来经过的时间。

long lLastClickTime = Long.MIN_VALUE;

public void onMousePress(Location point) {
   final long lCurrentTime = System.currentTimeMillis();
   if(lCurrentTime - lClickLastTime >= 1000) {
      mouseClicks++;
      lLastClickTime = lCurrentTime;
   }         
}