简体   繁体   English

有没有一种简单的方法可以从键盘上获取字符而无需在Java中按Enter键?

[英]Is there an easy way to get characters from the keyboard without hitting enter in Java?

I'd like to know if there is an easy way to get character input from a JTextField in Java as they happen, not after an enter keystroke. 我想知道是否有一种简便的方法可以从Java中的JTextField获取字符输入,而不是在输入击键之后获取。

In my case I want the characters (text) to be read in, and when the enter key is hit, do something with the characters already collected. 在我的情况下,我希望读取字符(文本),然后按Enter键时,对已经收集的字符进行处理。

尝试在JTextField上添加KeyListener

While there are ways to listen for keypress events, it seems like for the task you want to do you should wait until the enter keystroke and then do what you need to do there referencing the value of the jtextfield. 虽然有多种方法可以侦听按键事件,但是对于您要执行的任务,似乎应该等到输入击键,然后再执行引用jtextfield值的操作。 The jtextfield is already reading in the characters the user types, you don't need a custom handler to duplicate that (unless you really want to do it character by character, and include non-text character (ie "heg[backspace]llo[enter]" is somehow treated differently than "hello[enter]"). jtextfield已经在读取用户键入的字符,您不需要自定义处理程序来重复该操作(除非您真的想逐个字符地进行处理,并且包括非文本字符(即“ heg [backspace] llo [ enter]”在某种程度上与“ hello [enter]”不同。

您可以将DocumentListener添加到JTextField的文档中,即

textField.getDocument().addDocumentListener(...);

Is the user allow to paste text? 用户是否可以粘贴文本? (Can they right click and select paste?) (他们可以右键单击并选择粘贴吗?)

If so, KeyListeners won't work and you'll need DocumentListeners. 如果是这样,KeyListeners将不起作用,您将需要DocumentListeners。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM