How to write an equivalent of KeyListener with JLi

2019-05-28 23:30发布

问题:

I am working on a console application written in Java. What I have to do is handle user keyboard input. When a long process in launched with our program in a terminal, the user must have the possibility to press 'q' at anytime to stop the process (which is running on a separate thread).

I've tried several things :

  • Running in another different thread something that read user input and throws an InterruptedException to the process' thread
  • Using JLine and its ConsoleReader
  • Using JLine and add a TriggeredAction linked to a keyboard key

But each time, I face the same problem : the user has to press ENTER key, and I don't want that.

Thanks for help if you have any ideas, or the actual solution of my problem.

PS : Please, if you think this is impossible, don't answer. I know it's possible.

回答1:

Perhaps you could use one of these libraries,

http://sourceforge.net/projects/jxgrabkey/ for linux

https://code.google.com/p/jintellitype/ for windows

Less related with your question, but I think can help you,

http://sourceforge.net/projects/javacurses/

The problem, with all of this, is that you will lost the platform independence.