我正在创建一个应用程序,我想要一个功能,当用户按下E时,它会将鼠标指针设置到屏幕的中心(使用moveMouse()
方法).然而,它只给了我IlLegalStateException异常
分.
我试着用GlassRobot
来代替(从this个问题中得到一个可接受的答案),但这只给了我一个IllegalAccessException
.我做错了什么?我需要加点什么吗?
Code and Error
IlLegalStateException异常
100:下面有一条 comments
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1082)
Caused by: java.lang.ExceptionInInitializerError
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
... 5 more
Caused by: java.lang.IlLegalStateException异常: This operation is permitted on the event thread only; currentThread = main
at javafx.graphics/com.sun.glass.ui.Application.checkEventThread(Application.java:447)
at javafx.graphics/javafx.scene.robot.Robot.<init>(Robot.java:70)
at com.galactify.tiles/com.galactify.tiles.HelloApplication.<clinit>(HelloApplication.java:37) // This is where the Robot object is created
... 11 more
场景机器人宣言
private static final Robot robot = new Robot() ;
玻璃机器人宣言
private static final Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot() ;
Methods used to set the mouse pointer to the center when user presses E
static void onKeyReleased(KeyEvent evt) {
KeyCode key = evt.getCode() ;
out.println(key + " is released") ;
switch (key) {
case F11 -> {
stage.setFullScreen(!isFullscreen) ;
isFullscreen = !isFullscreen ;
}
case C -> {
stage.close() ;
isClosed = true ;
}
case E -> setupInventory() ;
}
}
static void setupInventory() {
robot.mouseMove((double) screenWidth / 2, (double) screenHeight / 2) ;
}