无需按“Enter”键即可从键盘读取内容使用 JCurses
我正在编写一个应用程序,要求我从控制台读取密钥,而不必等待用户按 Enter 键。我读到 JCurses 库可以提供帮助。
我尝试像这样使用 Toolkit.readCharacter() :
InputChar c = Toolkit.readCharacter();
system.out.println(c.getCharacter());
但问题是,无论输入多少个字符,readCharacter() 方法都不会结束执行。即使你按下回车键,它似乎仍然在等待你输入一个字符。
我真的很感谢任何使用 JCurses 的帮助,或者任何其他方式都可以。
I am writing an application that requires me to read a key from console without having to wait for the user to hit enter. I have read that JCurses library could help.
I tried using Toolkit.readCharacter()
like this:
InputChar c = Toolkit.readCharacter();
system.out.println(c.getCharacter());
But the problem was that the readCharacter()
method does not end execution no matter how many characters you input. Even if you press enter, it still seems that it is waiting for you to enter a character.
I really appreciate any help using JCurses, or any other way would do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java Curses 有一些特定的击键识别方法,但是将自己绑定到外部库来实现单个函数可能不是最好的解决方案。
您所追求的可以通过创建终端样式的 Swing 应用程序并使用
KeyListener
来检测击键事件来实现。但是,MadProgrammer 在 如何让 esc 停止方法 这样的解决方案可能存在“焦点问题”。因此,如果您想跟踪特定的击键,或者想根据不同的用户输入影响程序行为,我建议使用 键绑定 作为 Swing 的一部分实现。
例如
,其中 component 是任何
JComponent
对象(可能是终端显示),而yourAction
是任何 Swing 操作。对于“控制台”应用程序来说,使用此处所示的 getInputMap() 参数化形式更适合,因为用户必须在顶级窗口中进行击键,因此组件焦点是无关紧要的。Java Curses has a couple of specific keystroke recognition methods, but tying yourself down to an external library for a single function may not be the best solution.
What you are after could be achieved by creating a terminal-style Swing application, and using a
KeyListener
to detect keystroke events. However, MadProgrammer notes in How to make esc stop a method that such a solution may have "focus issues".So if you want to trace specific keystrokes, or want to affect program behaviour based on different user inputs, I would recommend using key bindings which are implemented as part of Swing.
e.g.
Where component is any
JComponent
object (assumably a terminal display), andyourAction
is any Swing action. Using the paramaterised form ofgetInputMap()
as shown here is preferable for a "console" application, as the user will necessarily making keystrokes within the top level window, and therefore component focus is irrelevant.这个程序对我有用。
您需要调用 Toolkit.init() 将终端置于 cbreak() 模式。
请记住在退出之前调用 Toolkit.shutdown()。
有几个缺点。
节目。
This program worked for me.
You need to call Toolkit.init() to put the terminal into cbreak() mode.
And remember to call Toolkit.shutdown() before exiting.
A couple of drawbacks.
The program.