[Chapter 8] 8.4 Extending TextField
Author: John Zukowski
Date: Thu Jul 31 14:42:04 1997

#

| Chapter 8 Input Fields |

## 8.4 Extending TextField

To extend what you learned so far, Example 8.1 creates a sub-class of `TextField` that limits the number of characters a user can type into it. Other than the six constructors, all the work is in the `keyDown()` method. The entire class follows.

#### Example 8.1: The SizedTextField Class Limits the Number of Characters a User can Type

    import java.awt.*;
    public class SizedTextField extends TextField {
        private int size;  // size = 0 is unlimited
        public SizedTextField () {
            super ("");
            this.size = 0;
        }
        public SizedTextField (int columns) {
            super (columns);
            this.size = 0;
        }
        public SizedTextField (int columns, int size) {
            super (columns);
            this.size = Math.max (0, size);
        }
        public SizedTextField (String text) {
            super (text);
            this.size = 0;
        }
        public SizedTextField (String text, int columns) {
            super (text, columns);
            this.size = 0;
        }
        public SizedTextField (String text, int columns, int size) {
            super (text, columns);
            this.size = Math.max (0, size);
        }
        public boolean keyDown (Event e, int key) {
            if ((e.id == Event.KEY_PRESS) && (this.size > 0) &&
                (((TextField)(e.target)).getText ().length () >= this.size)) {
                // Check for backspace / delete / tab--let these pass through
                if ((key == 127) || (key == 8) || (key == 9)) {
                    return false;
                }
                return true;
            }
            return false;
        }
        protected String paramString () {
            String str = super.paramString ();
            if (size != 0) {
                str += ",size=" + size;
            }
            return str;
        }
    }

Most of the `SizedTextField` class consists of constructors; you really don't need to provide an equivalent to all the superclass's constructors, but it's not a bad idea. The `keyDown()` method looks at what the user types before it reaches the screen and acts accordingly. It checks the length of the `TextField` and compares it to the maximum length. It then does another check to see if the user typed a Backspace, Delete, or Tab, all of which we want to allow: if the field has gotten too long, we want to allow the user to shorten it. We also want to allow tab under all circumstances, so that focus traversal works properly. The rest of the logic is simple:

- If the user typed Backspace, Delete, or Tab, return `false` to propagate the event.

- If the field is too long, return `true` to prevent the event from reaching the peer. This effectively ignores the character.

TextArea |  | Pick Me