The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


JPasswordField with an empty echo character: the fix

Posted by zixle on December 19, 2005 at 3:38 PM PST
In my last blog I explained how to customize the visual feedback provided by JPasswordField. Unfortunately the first option I detailed, specifying a character that takes no space, had a bug in it. This blog discusses the bug and how to fix it. If you want to cut to the chase and run the demo it can be found here.

Specifying you want JPasswordField to render a character with no space is as easy as:

passwordField.setEchoCharacter('\u200b');
As my last demo illustrated, this will produce an ArithmeticException when you click on the password field (second one in the demo). As you could probably guess the exception occurs because PasswordView is dividing the width of the character without checking it, resulting in the exception. The fix is to create a subclass of PasswordView that overrides viewToModel without dividing by the character width. Here's the code:
  public int viewToModel(float fx, float fy, Shape boundsAsShape, Position.Bias[] bias) {
    boundsAsShape = adjustAllocation(boundsAsShape);
    Rectangle bounds = (boundsAsShape instanceof Rectangle) ?
                (Rectangle)boundsAsShape : boundsAsShape.getBounds();
    if (fx < bounds.x) {
      return getStartOffset();
    }
    return getEndOffset();
  }
With a character that takes up no space there's no way for the user to click anywhere but the beginning or end of the text. As such, viewToModel will return one of these.

To install this View you need to do something similar to that of the last blog (refer to it for more details). Create a custom JPasswordField, with a custom UI that returns the new View:

  new JPasswordField() {
    public void updateUI() {
      setUI(new BasicPasswordFieldUI() {
        public View create(Element elem) {
          return new EmptySpacePasswordView(elem);
        }
      });
    }
  };
And here's the demo.

That's enough for passwordfield and text, next time around something new.

Related Topics >> J2SE      
Comments
Comments are listed in date ascending order (oldest first)