tags:

views:

58

answers:

2

So, I'm working with swing and I need to find a clean (non-CPU-hogging-way) to introduce a delay on a text field. Basically, users will enter a number into this field and the keyReleased() event checks that the input fits a few parameters and then assigns the value to a data storage element in the program. If the data is invalid, it displays a message. Since the routine is called every time they type a letter (unless they type VERY fast), the input process becomes quite annoying (as in general one or two characters of data are not going to fit the allowed parameters).

I've tried setting up a timer object and a timer task for it, however it doesn't seem to work very well (because it delays the thread the program is running on). The option to just wait until the data reaches a certain length is also not possible since (as state before) the input can vary in length.

Anyone got any ideas? Thanks!

+3  A: 

I've done stuff like this fairly frequently, and I have two suggestions.

The standard way of dealing with this is to use the InputVerifier class. This however only operates when the input component loses focus - it's designed to prevent the user navigating out of an input field when it's invalid, but it doesn't check until then.

The other way I've done this is to check validity on every keystroke, but not to bring up a message when it's invalid. Instead use a color to indicate validity - e.g. color it red when its invalid and black when valid. This isn't nearly as intrusive as the message. You can use a tooltip to give more detailed feedback.

You can also combine these methods.

DJClayworth
Doing validation that notifies the user of an error on defocus is definitely my preferred way. +1 for that.
aperkins
+3  A: 

Write a custom DocumentFilter. Read the section from the Swing tutorial on Text Component Features for more information.

camickr