I'm trying to track the position of the mouse cursor and thus need to use a thread to continue tracking it. My thread is running only once. I'm guessing that I have missed something along the way.
The code :
mousePosition class
import java.awt.MouseInfo;
import java.awt.Point;
import java.util.Timer;
public class mousePosition implements Runnable
{
static Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
static Timer t = new Timer();
int x,y = 0;
public void run()
{
try
{
x = mouseLocation.x;
y = mouseLocation.y;
System.out.println("X:"+x+" Y:"+y+" at time "+System.currentTimeMillis());
}
catch(Exception e)
{
System.out.println("Exception caught : "+e);
}
}
}
main class
public class threadRunner
{
public static void main(String[] args)
{
Thread t1 = new Thread(new mousePosition());
t1.start();
}
}
Thank you for any help. I know that this question was asked before but I am still struggling to make it work.
The Thread's run() method will only run once. It would run much more if you did something like this:
public void run() {
while(true) { // Or with a stop condition
try {
x = mouseLocation.x;
y = mouseLocation.y;
System.out.println("X:"+x+" Y:"+y+" at time "+System.currentTimeMillis());
} catch(Exception e) {
System.out.println("Exception caught : "+e);
}
}
}
Although I'm sure this while loop on a thread is expensive, speaking in computational cost, and there is a better practice using the Observer design pattern. An implementation and example of this good practice, is just precisely the MouseListener.
When you start() a new Thread, the only thing that happens is that the Threads run() method is executed. Once the run() method is finished, the Thread dies.
To continually check the mouse position, you should probably start some kind of MouseListener instead, there is a nice tutorial here.
To learn more about threads, I recommend looking throw the Java Tutorials on the subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With