我正在使用包含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.
更多推荐
发布评论