问题
This probably sounds simple and stupid, but for the life of me I cannot find a way to have a mouse listener which does mousePressed without having to be on a component. void mousePressed(){} doesn't seem to work the way I want it to.
Essentially I am making a java program which aims to work without graphics, and does things in the background. So if you click in chrome for example it still will effect the program.
What I was trying was this, which I realize is horribly incorrect.
class MKeyListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
moveMouse.playing = false;
}
}
As reccomended I tried the JNativeHook library, however it doesn't seem to work the way I think it should:
public class mousepresstest implements NativeMouseInputListener{
@Override
public void nativeMouseClicked(NativeMouseEvent e) {
System.out.println("worked");
}
}
It doesn't print the text on mouse pressed, am I missing something here?
回答1:
Java Mouse listeners are only meant for swing/awt components and that too from the same running process.
If you want to listen for mouse/keyboard events from other apps use the JNativeHook library.You can install a global keyboard hook and listen for keypress or a mousehook for mouse events.You do not need to use Swing or other GUI classes.
Internally JNativeHook uses JNI to provide these functionality.
来源:https://stackoverflow.com/questions/20649536/java-mouse-listener