简体   繁体   中英

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.

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.

尝试在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. 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]").

您可以将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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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