开发者

Returning a JTextField to editing after a warning dialog

开发者 https://www.devze.com 2023-01-10 18:37 出处:网络
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

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 flas开发者_StackOverflow中文版hing 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号