views:

210

answers:

4

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.

+7  A: 

Try adding a KeyListener on the JTextField

Kevin
Thanks Kevin, I will have a look at that.
Fred
+3  A: 

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

Brian Schroth
Is there no way of excluding control characters perhaps by defining a range or giving some pre-defined constant as an argument? I had a look at a keystroke class but it seemed more aimed at controlling games and so on, but from what I understood you could register what key you were interested in. But I just looked it over briefly.
Fred
Brian has the best answer so far. Control characters won't end up in the text field's text string anyway, the text from there is good to go. And no, you can't register for individual characters. What you SHOULD do, though, is register a keyListener to process the ENTER, when it happens. You'll want to shift to the next field or something then.
Carl Smotricz
+1  A: 

You can add a DocumentListener to the JTextField's document i.e.

textField.getDocument().addDocumentListener(...);
That looks interesting as well, thanks.
Fred
+1  A: 

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.

Milan Ramaiya
Hmm, that's interesting, I haven't thought about that.
Fred