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 开发者_Python百科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.
Try adding a KeyListener on the JTextField
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 (i.e. "heg[backspace]llo[enter]" is somehow treated differently than "hello[enter]").
You can add a DocumentListener to the JTextField's document i.e.
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.
精彩评论