我想跟蹤鼠標光標的位置,因此需要使用一個線程來繼續跟蹤它。我的線程只運行一次。我猜測我錯過了一些東西。爲什麼線程只運行一次?
代碼:
mousePosition類
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);
}
}
}
主類
public class threadRunner
{
public static void main(String[] args)
{
Thread t1 = new Thread(new mousePosition());
t1.start();
}
}
感謝您的任何幫助。我知道這個問題以前曾被問過,但我仍然在努力使其工作。
由於沒有循環,並且您不使用計時器,所以'run'方法只運行一次是有道理的。 – assylias 2012-07-20 11:42:00
你爲什麼不在你的線程中使用你的計時器?線程的'run()'方法將在執行代碼並結束您的線程後始終返回! – 2012-07-20 11:45:14
你通常在run方法中有一些while語句,以保持線程正常運行,而且經常是真的 – 2012-07-20 11:46:40