问题
got my first question and here it goes.
I'm programming in java and making a litte program where I would like to track mouse event and make some statistics. For example number of right/left clicks, movements, time between doubleclicks, averages, etc.
However I'm not able to make a little program and let in run in the background without any gui components in java. I'm not able to test my program and let it (for example) print lines in the console (in eclipse) for the events it gets from the mouse without resorting to a gui.
I have not found anything where a mouselistener is used without a JPanel or where I can use a mouselistener without a gui. Is it not possible in java or are there ways I can get around this?
Thanks in advance!
回答1:
While this can be done with Java using JNI or JNA or other tools that are needed in order to get Java closer to the OS, please understand that Java has been built to be as operating system agnostic as possible -- in other words it was built so that this sort of thing would be very hard to do without jumping through the hoops mentioned. Your best bet, I think, is to use a tool that does get closer to the OS, such as C++ for all or C# or AutoIt (I recommend the latter highly) if Windows and other other similar tools for other OS's.
回答2:
Despite everything @hovercraft-full-of-eels (correctly) said, It's still possible without any native code.
However, you have to poll for mouse events instead of listenning to them.
Try this:
import java.awt.MouseInfo;
public class MouseWithoutGUI {
public static void main(String[] args) throws Exception {
while (true) {
System.out.println(MouseInfo.getPointerInfo());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
You can write an event based system on such a polling loop, to make it look like you are listenning to events.
It has a lot of downsides, I know. But it might be sufficient for your needs.
来源:https://stackoverflow.com/questions/27473808/mouselistener-without-a-gui