我一直在尝试用 java 编写这个自动点击器大约 7 个小时。我根据别人的代码写了一些,有些是我自己写的。我使用 JNativeHook 在 Eclipse/控制台之外的窗口中捕获点击。
想法是这样的:当您按住左键单击时,机器人将为您左键单击,每次单击之间有 300 毫秒。
然而,问题是当我左键单击时,我没有执行代码来使机器人运行。当我添加“test.run();”行时 在 nativeMousePressed 侦听器中,是的,它确实自动单击,但是当我释放左键单击时,它仍然运行。然后停止它的唯一方法是单击 eclipse 上的停止按钮。
现在,我知道我需要让它在一个新线程中运行,这样我仍然可以使用它的侦听器,我试图在我的 MousePressed 侦听器中这样做:
Thread test = new Thread(new Runnable() {
public void run() {
try {
Robot robot = new Robot();
System.out.println("GOT HERE 1");
System.out.println("Got HERE 4");
try {
Thread.sleep(300);
System.out.println("Got HERE 5");
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
// robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
System.out.println("Got HERE 6");
// if ();
} catch (InterruptedException ex) {
}
} catch (AWTException e1) {
}
;
}
});
我已经删除了我的循环,因为这似乎没有做任何改变它。有人可以向我解释这里出了什么问题吗?
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.mouse.NativeMouseEvent;
import org.jnativehook.mouse.NativeMouseInputListener;
public class AutoClicker implements NativeMouseInputListener {
public void nativeMouseClicked(NativeMouseEvent e) {
// dont need
}
public void nativeMousePressed(NativeMouseEvent e) {
if (e.getButton() == NativeMouseEvent.BUTTON1) {
System.out.println("Mouse Pressed: " + e.getButton());
run = true;
System.out.println(run);
Thread test = new Thread(new Runnable() {
public void run() {
try {
Robot robot = new Robot();
System.out.println("GOT HERE 1");
System.out.println("Got HERE 4");
try {
Thread.sleep(300);
System.out.println("Got HERE 5");
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
// robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
System.out.println("Got HERE 6");
// if ();
} catch (InterruptedException ex) {
}
} catch (AWTException e1) {
}
;
}
});
}
}
public void nativeMouseReleased(NativeMouseEvent e) {
if (e.getButton() == NativeMouseEvent.BUTTON1) {
System.out.println("Mouse Released: " + e.getButton());
run = false;
System.out.println(run);
}
}
public void nativeMouseMoved(NativeMouseEvent e) {
// dont need
}
public void nativeMouseDragged(NativeMouseEvent e) {
// dont need
}
public void click() {
}
public static boolean run = false;
public static void main(String[] args) {
try {
GlobalScreen.registerNativeHook();
} catch (NativeHookException ex) {
System.err.println("There was a problem registering the native hook.");
System.err.println(ex.getMessage());
System.exit(1);
}
Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
logger.setLevel(Level.WARNING);
// Don't forget to disable the parent handlers.
logger.setUseParentHandlers(false);
// Construct the example object.
AutoClicker clicker = new AutoClicker();
// Add the appropriate listeners.
GlobalScreen.addNativeMouseListener(clicker);
}
}