Search code examples
javaswingawtmouseeventmousemotionevent

In Java, how do I find the time since the last mouse moved?


Say, for example, if I have a circle drawn in a JFrame, and I want to paint over it if I hover over it for three seconds.

I've got a MouseMotionListener that tells me the point of the cursor in the JFrame, but so far that's about it.

public void mouseMoved(MouseEvent e)
{
  PointerInfo a = MouseInfo.getPointerInfo();
  cursorPos = a.getLocation();
  SwingUtilities.convertPointFromScreen(cursorPos, e.getComponent());
}

I'm still quite new to action listeners. What should I add if I want to test if the mouse is not moving?

Also, I'm just curious, why is it that MOUSE_MOVED in MouseEvent is considered an int?


Solution

  • Going backwards through your questions.

    Why is it that MOUSE_MOVED in MouseEvent is considered an int?

    All of the mouse constants are ints. That's how enumeration was done in Java before version 1.5.

    How do I find the time since the mouse last moved?

    In your mouseMoved method, you save the current time somewhere in your GUI model. You then write a method in your GUI model that returns the idle time.

    idleTime = System.currentTimeMillis() - savedTimeinMillis.
    

    You divide the idle time by 1000 for seconds.