0

I am trying to write a program which detects "idle" status but I don't see the problem in my code. Could someone help me please with an useful tip? Here's my code:

package idlestatus;

import java.awt.MouseInfo;

public class Idlestatus {

    public static void main(String[] args) throws InterruptedException {
        Integer firstPointX = MouseInfo.getPointerInfo().getLocation().x;
        Integer firstPointY = MouseInfo.getPointerInfo().getLocation().y;
        Integer afterPointX;
        Integer afterPointY;
        while (true) {
            Thread.sleep(10000);
            afterPointX = MouseInfo.getPointerInfo().getLocation().x;
            afterPointY = MouseInfo.getPointerInfo().getLocation().y;
            if (firstPointX == afterPointX && firstPointY == afterPointY) {
                System.out.println("Idle status");
            } else {
                System.out.println("(" + firstPointX + ", " + firstPointY + ")");
            }
            firstPointX = afterPointX;
            firstPointY = afterPointY;

        }

    }
}

2 Answers2

0

If is working but your condition is always getting false, because you are using Integer instead of primitive int. Note that when you use Object, compare them with .equals() method instead of ==.

Therefore :

if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY)) {
    //your code...
}

See this for difference between == and Object.equals() method.

And as mentioned in comments, you can always use int for such purposes, instead of Integer.

See this for difference between Integer and int.

Kaushal28
  • 4,823
  • 4
  • 30
  • 57
0

You are comparing two objects memory addresses , which is Integer object(wrapper class).

if (firstPointX == afterPointX && firstPointY == afterPointY) 

What you want to do is compare values in these two objects. To do that you need to use like below:

if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY))

Wrapper / covering classes:

  • There is a wrapper class for each primitive data type.
  • Primitive types are use for performance reasons(Which better for your program).
  • Cannot create objects using primitive types.
  • Allows a way to create objects and manipulate basic types(i.e. converting types).

Exsample:

Integer - int
Double - double
Blasanka
  • 14,208
  • 6
  • 76
  • 90