Java keyboard input parsing in a console app
Asked Answered
W

2

9

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.

Wenwenceslaus answered 5/1, 2009 at 19:38 Comment(1)
Could you post an snipped of the answer? Looks very interesting.Keyhole
M
4

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.

Mae answered 9/1, 2009 at 20:25 Comment(0)
M
3

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

Midi answered 5/1, 2009 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.