感谢所有建议通过将类实例传递给我的 MouseListener 类来解决问题。
对于遇到同样问题的任何人:
public boolean activate;
public boolean toggled;
private Robot robot;
public MouseListener mouseListener = new MouseListener();
public KeyboardListener keyListener = new KeyboardListener();
public static Game instance;
public Game() {
this.activate = false;
// this.toggled = false;
try {
GlobalScreen.registerNativeHook();
GlobalScreen.isNativeHookRegistered();
GlobalScreen.addNativeMouseListener(mouseListener);
GlobalScreen.addNativeKeyListener(keyListener);
} catch (NativeHookException e) {
e.printStackTrace();
}
}
public void run() {
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
while(true) {
try {
Thread.sleep(1L);
if(Game.this.isActivate()) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(100);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean isActivate() {
return activate;
}
public void setActivate(boolean activate) {
this.activate = activate;
}
public boolean isToggled() {
return toggled;
}
public void setToggled(boolean toggled) {
this.toggled = toggled;
}
**public static Game getGame() {
if(Game.instance == null) {
Game.instance = new Game();
}
return Game.instance;
}**
这是将“激活”更改为“真”的类。
public void nativeMouseClicked(NativeMouseEvent e) {
// nothing
}
public void nativeMousePressed(NativeMouseEvent e) {
if(e.getButton() == NativeMouseEvent.BUTTON1) {
Game.getGame().setActivate(true);
}
}
public void nativeMouseReleased(NativeMouseEvent e) {
if(e.getButton() == NativeMouseEvent.BUTTON1) {
Game.getGame().setActivate(false);
}
}
}