Skip to main content

JPasswordField with an empty echo character: the fix

Posted by zixle on December 19, 2005 at 3:38 PM PST

In my href="">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 href="">here.

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


As my last href="">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

Related Topics >>