views:

15

answers:

1

Hello,

Is there a way to validate text in a JTextField while you type, based on what you already typed in that field? Should I create a keyEventListener of some sort, or is there a way to override the insertString method to let it do that. I prefer the latter, but it only gives you control over the last character that was typed, not the entire string of text already present in the text field. I want it to beep as soon as one tries to enter more than one decimal point, and not adding that second decimal point to the text field.

Thanks for your help, Erik

A: 

What's the problem with adding a listener? That's what they are there for.

You might also want to have a look at JFormattedTextField.

musiKk
It's not that I'm against listeners, but the insertString method seemed very convenient to detect any wrong input. If I'm using a listener like documentListener wouldn't it first put the text in the textField, then detect that there is wrong stuff there and then reformat the text and beep? It feels like an extra step, but it could be me.
FinalArt2005
Most probably, yes. Maybe JFormattedTextField handles this different. Another possibility is not to remove the second decimal point but to draw a red border around the text field, write a message or disable the OK button (or equivalent) as long as the input is invalid. I find it confusing if just nothing happens. It could mean that I didn't push they key on the keyboard hard enough or something.
musiKk
You're right at that I guess. Even though I do fire a beep, one might not hear this, so that's something I could think about. I looked at the JFormattedTextField and it seems to do just what you describe: verifying and optionally with a little bit of code keeping the focus on that field. I'm still curious though if there isn't some way to validate based on more than just the last character before the stuff is being shown in the textField, but I guess a listener is fast enough for simple user input. Thanks for the help!
FinalArt2005