改变焦点之前的Java Swing调用方法(Java Swing Call Method Before Focus Change)

编程入门 行业动态 更新时间:2024-10-22 20:37:20
改变焦点之前的Java Swing调用方法(Java Swing Call Method Before Focus Change)

我正在使用包含JTextField的java swing表单 。 文本字段需要输入验证,当字段丢失集中时执行验证。 即单击除了字段本身之外的任何软件。

该表单还包含一个JButton来清除(取消)表单。 现在每当我按下取消按钮并且Textfield是当前聚焦的组件时,就会调用验证功能。 这不应该发生。

我曾尝试过InputVerifier和Focuslistener

有没有办法让我知道哪个组件导致焦点发生变化?

I am working with a java swing form that contains a JTextField. The text field needs input validation , validation is performed when the field losses focus . i.e clicking anyware apart from the field itself.

The form also contains a JButton to clear(cancel) the form . Now whenever I press the cancel button and the Textfield is the currently focused component the validation function is invoked. This should not happen.

I have tried InputVerifier and Focuslistener

Is there a way I can know what component caused the focus to change ?

最满意答案

您可以使用FocusListener对focusLost事件做出反应。 在那里你可以通过FocusEvent getOppositeComponent()获取焦点的目的地。 如果目的地是清除/取消/不管按钮什么都不做,否则验证。

这是一个非常基本的例子:

JTextField textField = new JTextField(15); textField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { Component comp = e.getOppositeComponent(); if (comp instanceof JButton) { JButton button = (JButton) comp; String buttonText = button.getText(); if (buttonText.equals("Cancel")) { return; } } // do the validation System.out.println("validate"); } });

其实camickr的解决方案比我的上面简单得多。 我不知道是否有解决方案。

You can use a FocusListener to react to a focusLost event. There you can retrieve the destination of the focus via getOppositeComponent() from the FocusEvent. If the destination is the clear/cancel/whatever button do nothing, otherwise validate.

A very basic example for this:

JTextField textField = new JTextField(15); textField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { Component comp = e.getOppositeComponent(); if (comp instanceof JButton) { JButton button = (JButton) comp; String buttonText = button.getText(); if (buttonText.equals("Cancel")) { return; } } // do the validation System.out.println("validate"); } });

Actually camickr's solution is a lot simpler than mine above. I had no idea that there was built in solution for this.

更多推荐

本文发布于:2023-04-29 09:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   焦点   Swing   Java   Change

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!