我正在编写一个程序,它将在给定的时间段内将鼠标移动一定距离。所以我需要算法去:
点击开始
while(true){
move mouse to point x
sleep for n seconds
}
哪个有效,但是当作为线程运行时,仍然按下启动按钮,因为线程一直在运行。因此,我什至无法退出该程序(与任何无限循环一样),并且我无法将布尔值设置为“false”以停止 while 循环。我需要做什么才能使该线程可以在后台运行并且仍然允许我单击停止按钮并使鼠标停止移动?
在我的主要课程中,我有:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
Thread t = new Thread(new Mover(1000, true));
t.run();
}
}
线程类:
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Robot;
public class Mover implements Runnable {
int time;
boolean startStop;
public Mover(int x, boolean b) {
time = x;
startStop = b;
}
@Override
public void run() {
while (startStop) {
// TODO Auto-generated method stub
//Get x position
int intX = MouseInfo.getPointerInfo().getLocation().x;
// String intx = Integer.toString(intX);
//Get y position
int intY = MouseInfo.getPointerInfo().getLocation().y;
Robot robot;
try {
robot = new Robot();
robot.mouseMove(intX - 100, intY);
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// Close while loop
}
}