Thursday, April 8, 2010

Input Validation in Swing

Swing provides built-in text field validation. JComponent has method "setInputVerifier" and this method accepts implementations of abstract class called InputVerifier. InputVerifier has only one method that developer has to implement:

boolean verify(JComponent input)

This method must return true if input is valid and false otherwise. It cann't be easier.

However there are some glitches. For example, it seems that it only hijacks focus for text components, because checkboxes and buttons remain clickable and fully functional. To overcome this problem (and also for usability) I started to show JOptionPane on invalid inputs. Now, when my text field tries to loose focus, JOptionPane hijacks it from targeted buttons or checkboxes and shows error, and after disappearing text field is again focused.

    port.setInputVerifier(new InputVerifier() {
      public boolean verify(JComponent input) {
        String value = port.getText();
        int port = -1;
        try {
          port = Integer.parseInt(value);
        } catch (NumberFormatException e) {
        }
        if ((port > 0) && (port < 65535)) {
          return true;
        } else {
          JOptionPane.showMessageDialog(settings, "Port must be number between 0 and 65535", "Input error", JOptionPane.ERROR_MESSAGE);
          return false;
        }
      }
    });


So it works fully as expected. Basically, this simple use case is exactly what I needed, so I am quite happy with this InputVerifier. However, for some more advanced or trickier situations there maybe still necessary to create some little custom framework.

No comments:

Post a Comment