views:

23

answers:

1

In my application I have a JTextField that will only allow the user to fill it with input formatted in a certain way. I have a method that checks if input into the field is valid and if not it displays a dialog. After this occurs I would like the focus to return to the text field so that the user can correct there mistake and type in the appropriately formatted input. I tried to do this by having the JTextField call requestFocus() on itself but this seems to only half work. The JTextField displays the flashing cursor but I cannot actually type in any text until I click on the text field again. Is there another method I need to call? I could not find anything else in the documentation.

+1  A: 

It's not exactly the solution you asked for, but you might want to look at javax.swing.InputVerifier. This object allows you to verify the input to a field and prevent taking focus away from it if the format isn't right. I don't think it would allow you to put up a dialog explaining the error (though it might - try it) but it would certainly allow you to put a message in a 'message area'.

What you do is set an InputVerifier on the JComponent, have it test the contents for validity; if it isn't right then the JComponent won't release focus (and can write an error message).

DJClayworth