控制台应用程序中的 Java 键盘输入解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/414237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 12:17:22  来源:igfitidea点击:

Java keyboard input parsing in a console app

javakeyboardjline

提问by Jason S

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

我刚刚开始使用JLine来解析控制台模式下的字符输入。它似乎运作良好,但我想知道:

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

JLine 中是否有非阻塞方式来确定字符是否可用?(即就像kbhit()在 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.

编辑:这是逐字符解析。我不会使用 GUI。Java 中控制台模式下的常用 InputStream I/O 要求您先按 Enter 键(例如,它仅是缓冲输入)。请不要告诉我在控制台模式下逐字符输入在 Java 中是不可能的;不是。JLine 使用具有平台相关实现的可移植接口来做到这一点。

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.

编辑更新:我能够在工作线程中编写一个辅助类来执行阻塞 I/O(使用 JLine 进行每个字符的 I/O,警告:您必须自己解析 Ctrl-C!)然后进行通信通过带有 isempty() 例程的同步队列。对于我现在正在做的事情,这很好,但我真的很想知道在未来做这件事的好方法。

采纳答案by Ed Brannin

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 ConcurrentLinkedQueuefrom java.util.concurrent.

我认为执行此操作的“正确”方法是将所有阻塞 I/O 倒入非阻塞队列的工作线程。从java.util.concurrent看一下ConcurrentLinkedQueue

回答by Pyrolistical

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

您必须编写一个 Swing 应用程序并编写一个KeyListener

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

阅读本教程:http: //java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html