[英]How do I fire an action when the user leaves a JTextBox?
I've got a JTextField, and I'd like the system to do some processing on what the user typed whenever the user leaves the text field. 我有一个JTextField,我希望系统在用户离开文本字段时对用户键入的内容进行一些处理。 The ActionListener that you can add to just the JTextField only fires when the user presses enter, however.
但是,您可以添加到JTextField中的ActionListener仅在用户按下Enter键时触发。
I'd like the processing routine to run whenever the user leaves the text box by any means - tabs, clicks out of it, presses enter, etc. (The processing in question is to save the text the user typed to the appropriate data object, nothing fancy.) 我希望每当用户通过任何方式离开文本框时都运行该处理例程-选项卡,单击文本框,按Enter键等。(有问题的处理是将用户键入的文本保存到适当的数据对象中, 没有什么花哨。)
My google-fu has failed on this one: I'm confident that it's possible, I just can't see how. 我的google-fu在这方面失败了:我相信这是可能的,但我不知道如何做到。
Add a FocusListener
. 添加一个
FocusListener
。
It's worth noting that this is a relatively low-level listener. 值得注意的是,这是一个相对较低级别的侦听器。 On
JComboBox
it wont work unless you find the text field (and perhaps button) that the particular PL&F inserts. 在
JComboBox
,除非您找到特定PL&F插入的文本字段(甚至按钮),否则它将无法工作。 Swing is a bit odd that way (amongst many other ways). 这种方式摆动(在许多其他方式中)有些奇怪。
Although for my money, non-cosmetic changes that happen when focus leaves a field give poor user experience. 尽管用我的钱,当焦点离开视野时发生的非外观变化会带来糟糕的用户体验。 Much better to do any relevant changes on every change with a listener on the text field's document.
最好在文本字段文档中使用侦听器对每个更改进行任何相关更改。
If you want to edit the text as it is typed then you should use an DocumentFilter. 如果要编辑键入的文本,则应使用DocumentFilter。
If you want to validate the text as a complete entity then you can use an InputVerifier. 如果要验证文本是否为完整实体,则可以使用InputVerifier。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.