I have a JTextField with more then one FocusListener. If the first-called focusLost fails (for validation), how can I stop the next focusLost call?

Scott Stanchfield

Be very careful on this type of behavior...

First, listeners are intended to be completely independent of each other. There are two main reasons for this:

  • A problem in one listener should not impact another listener
  • The order of listener calls is not defined by the JavaBean specification

There are two exceptions to this rule:

  1. Constrained properties in a JavaBean talk to VetoableChangeListeners. The order of called listeners is not defined, but if any listener throws a PropertyVetoException, the remaining ones are not called.
  2. If you write your own events (under the Beans model, same type of pattern as existing AWT events), their behavior is defined by you. You can implement and document that they have a certain order or will stop when any listeners throw an exception.

    I strongly recommend against this as it's not normal behavior for event handling

Note that you cannot simply make the text property constrained. The problem is that the setText method for a constrained JTextField could throw a PropertyVetoException, which isn't declared in the setText method of JTextField.

There are really two things you can do here:

  1. You could write a custom event for this, and implement/document that it calls listeners in the added order and that if any throw an exception, the others are not called.
  2. Add a single focusLost listener that does the multiple validations in order, stopping if any fail.

I'd recommend the second approach, like the following:


JTextField f = new JTextField();
f.addFocusListener(new FocusListener() {
  public void focusGained(FocusEvent e) {}
  public void focusLost(FocusEvent e) {
    try {
      validation1();
      validation2();
      validation3();
    }
    catch(Exception e) {
      // report the validation error
    }
  }
});

If any of the validations fail (throw an exception), the others are not processed.

Finally, Don't forget that a call to setText() can change the value of the field!. You should override setText() and include validation as well.

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.