Java keyboard input parsing in a console app

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 04:20:40

问题


I've just started messing around with JLine to parse character input in console mode. It seems to work well, but I'm wondering:

Is there a nonblocking way in JLine to find out if characters are available? (i.e. like kbhit() in Windows.)

I suppose I could always wrap keyboard input in its own thread which then offers the keyboard characters in a thread-safe queue to the main thread, but that seems like it should be unnecessary.

EDIT: This is character-by-character parsing. I am not going to use a GUI. The usual InputStream I/O in Java in console mode requires you to hit the Enter key first (e.g. it's buffered input only). Please don't tell me character-by-character input in console mode is impossible in Java; it isn't. JLine does it using a portable interface with a platform-dependent implementation.

Edit update: I was able to hack together a helper class to do the blocking I/O in a worker thread (using JLine for the per-character I/O, warning: you have to parse Ctrl-C yourself!) & then communicate via a synchronized queue with an isempty() routine. For what I'm doing right now that's fine, but I would really like to know a Good Way To Do This In The Future.


回答1:


You seem to be on the right track.

I think the "right" way to do this is a worker thread that pours all the blocking I/O into a non-blocking queue. Hava a look at ConcurrentLinkedQueue from java.util.concurrent.




回答2:


You can't use a console to get non-blocking input without native libraries.

You'll have to write a Swing app and write a KeyListener

Read this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html



来源:https://stackoverflow.com/questions/414237/java-keyboard-input-parsing-in-a-console-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!