简体   繁体   English

用户离开JTextBox时如何触发动作?

[英]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.

相关问题 DocumentListener Java,如何防止JTextBox中出现空字符串? - DocumentListener Java, How do I prevent empty string in JTextBox? 用户离开并回来时如何保留JavaBean? - How do I have my JavaBean retain when a user leaves and comes back? 即使应用仍处于活动状态,当用户离开网站或关闭浏览器时,脚本事件也不会触发 - Scripting events no longer fire when a user leaves site or closes browser even though app is still active 如何去除二叉树的叶子? - How do I remove the leaves of a binary tree? 如何仅按TreeTableView中的叶子排序? - How do I sort by leaves only in a TreeTableView? 当用户留下空白 editText 时,如何设置 Toast 消息 - How can I set a Toast message when user leaves a blank editText 如何在绘制新的矩形时触发自定义事件? - How do I fire a custom event when a new Rectangle is drawn? 我将如何检查用户是否点击了由 fillRect 生成的正方形并在他们这样做时执行操作? - How would I go about checking if the user clicked on a square generated by fillRect & perform an action when they do so? 如何检测用户何时在JTabbedPane中离开某个选项卡 - How to detect when a user leaves a certain tab in a JTabbedPane 如何检查ConcurrentLinkedQueue是否为GC留下垃圾(已取消引用的实例)? - How do I check if ConcurrentLinkedQueue leaves garbage (dereferenced instances) for the GC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM