1

I need to implement a Java class that implements KeyListener. However, I don't need a JFrame or another awt/swing-based class. I only need a console application in Java.

I guess that I need to register my listener somewhere to let it working. How can I do this in a simple console application? I only find GUI-based examples.

Extreme Coders
  • 3,195
  • 2
  • 33
  • 49
mat_boy
  • 10,930
  • 19
  • 62
  • 103

1 Answers1

2

KeyListener is not meant for console apps. What you could do is read one character at a time using System.in.read()

Another method to have a sort of console KeyListener is by using the JNI. You can install a global keyboard hook and listen for keypress. The JNativeHook library will be useful if you want to do it in this way. You do not need to use Swing or other GUI classes.

Extreme Coders
  • 3,195
  • 2
  • 33
  • 49
  • There is a comment by [Peter Jaloveczki](http://stackoverflow.com/users/1960804/peter-jaloveczki) to [this](http://stackoverflow.com/questions/4005574/java-key-listener-in-commandline) post. What do you think about it? – mat_boy Jun 13 '13 at 08:43
  • @mat_boy that post talks about alternative techniques. not that actual `KeyListener` class can be used to do that.... – pinkpanther Jun 13 '13 at 08:46
  • @pinkpanther Yes, you are right! Is not the same, is not useful at all compared with the effectiveness of `KeyListener` interface. Maybe I have to lunch a JFrame and to hidden this frame to the user's sight! – mat_boy Jun 13 '13 at 08:47
  • @mat_boy Hiding the `JFrame` is also not possible as `KeyEvent` will only be generated if the `JFrame` has active focus – Extreme Coders Jun 13 '13 at 08:49
  • @ExtremeCoders Of course, I didn't reasoned about that! I think that I have no choice: I need a swing app! – mat_boy Jun 13 '13 at 08:50
  • @mat_boy See my updated answer – Extreme Coders Jun 13 '13 at 08:53
  • @ExtremeCoders Thank you! I'm gettin' a look! It seems interesting. – mat_boy Jun 13 '13 at 08:54