Formatted Text Entry
Several years ago, I took a course on the COBOL language and became acquainted with the concept of formatted text entry. Formatted text entry controls what characters are accepted during a text-entry operation and uses a mask to aid it in this task. A mask is a string of special characters that specify entry positions in which only digit characters are accepted, only uppercase letters are accepted, and so on; or where literal characters are displayed as is; or where no characters can appear during text entry. The following example demonstrates a phone number mask.
(999) 999-9999This phone number mask controls formatted text entry of phone numbers. The 9 characters identify entry positions for numeric characters only. When an entry field is displayed that conforms to this mask, underscore characters are displayed in the same positions as the 9 characters that appear in the mask. Furthermore, the parentheses (), space, and hyphen (-) literal characters are displayed as is. The following example demonstrates what the user sees on the screen.
(___) ___-____When this entry field is displayed, the blinking text entry caret is positioned at the first underscore that follows the opening parenthesis, (. The user can type alphabetic characters, but only numeric characters are accepted in the entry positions represented by underscores. As the user types numbers, the caret moves to the right, automatically skipping over the closing parenthesis ), the space, and hyphen (-) literal characters. Furthermore, the user can correct a mistake by pressing the Backspace key. However, only numbers are rubbed out: The parentheses, space, and hyphen characters are not erased by a Backspace operation.
Unfortunately, the AWT doesn't include a standard component for specifying and controlling formatted text entry. As a result, it's necessary to create this component. Before doing so, what mask characters should be used to control entry? I've chosen to use 9, A, a, and c (or _). As you've seen, a 9 accepts only a numeric character. In contrast, A accepts only an uppercase letter, a accepts only a lowercase letter, and c accepts any character. Also, an underscore _ can be substituted in place of c.
After some thought, I created a FormattedTextField class that is a subclass of the AWT's TextField class. This makes sense because a FormattedTextField is a TextField with formatted text-entry support. FormattedTextField declares a single constructor that takes two argumentsa mask and a validation flag. The mask describes entry positions and literal characters, whereas the validation flag determines whether input focus can leave the field before appropriate characters have been entered in all mask entry positions. If the mask argument doesn't contain at least one mask character (9, A, a, c, or _), the constructor throws an IllegalArgumentException object. The following code fragment demonstrates creating a FormattedTextField component object:
FormattedTextField ftf = new FormattedTextField ("(999) 999-9999", true);This code fragment creates a FormattedTextField component object that controls text entry of a telephone number. As it's important for all phone number digits to be entered before input focus is moved to another component, a Boolean true value is passed as the validation flag.
Without further adieu, Listing 5 presents the FormattedTextField source code.
Listing 5 The FormattedTextField component source code
// FormattedTextField.java // =================================================================== // The classes, methods, and field variables in this source file // should be documented with Javadoc-compliant comments. This // hasn't been done due to time constraints. However, as an exercise, // I'll leave it to you to provide such comments. // =================================================================== import java.awt.*; import java.awt.event.*; public class FormattedTextField extends TextField { // ============================================================== // The following four constants are used to differentiate between // mask characters 9, A, a, and c and their literal counterparts. // ============================================================== final static char ANYCHAR = '\u0000'; final static char DIGIT = '\u0001'; final static char LOWERCASE = '\u0002'; final static char UPPERCASE = '\u0003'; // ============================================ // The mask variable holds the formatting mask. // ============================================ private String mask; // ============================================================= // The index variable holds the next input position. This zero- // based number is relative to the first non-mask character // position. // ============================================================= private int index; // ============================================== // The len variable holds the length of the mask. // ============================================== private int len; // ========================================================== // The lastIndex variable holds the last mask entry position. // ========================================================== private int lastIndex; // ============================================================ // The startIndex variable holds the first mask entry position. // ============================================================ private int startIndex; // ============================================================== // The validate variable "decides" if a FormattedTextField should // be validated (at the character level) before focus switches. // ============================================================== private boolean validate; // =============================================================== // FormattedTextField (String mask, int nColumns, // boolean _validate) // // Construct a FormattedTextField object. // // Arguments: // // mask - formatting mask // // The following mask characters are recognized: // // 9 (digit only) // A (uppercase letter only) // a (lowercase letter only) // c (any character) // _ (can be used in place of c) // // Any other character is literally displayed. // // Example: // // (999) 999-9999 // // The ( ) and - characters are literally displayed. // Only digit characters can be typed wherever 9 appears. // // nColumns - minimum number of character columns to display // // This argument has the same meaning as TextField's // nColumns argument. // // _validate - field validation flag // // Pass true to validate field (at character level) // before allowing focus to proceed to next field. // Actually, focus does shift to the next field when // the Tab key is pressed. However, a call to request // the focus back to this component is made if the // input is invalid. // =============================================================== public FormattedTextField (String mask, int nColumns, boolean _validate) { // Pass nColumns to TextField constructor to initialize that // layer of this object. super (nColumns); // Save the field validation flag. validate = _validate; // Save the mask's length. len = mask.length (); // Convert mask characters c, 9, a, and A to their constant // equivalents. StringBuffer mask2 = new StringBuffer (mask); for (int i = 0; i < len; i++) if (mask2.charAt (i) == 'c') mask2.setCharAt (i, ANYCHAR); else if (mask2.charAt (i) == '9') mask2.setCharAt (i, DIGIT); else if (mask2.charAt (i) == 'a') mask2.setCharAt (i, LOWERCASE); else if (mask2.charAt (i) == 'A') mask2.setCharAt (i, UPPERCASE); mask = mask2.toString (); // Check to see if at least one mask character was specified. boolean found = false; for (int i = 0; i < len; i++) if (mask.charAt (i) == ANYCHAR || mask.charAt (i) == DIGIT || mask.charAt (i) == LOWERCASE || mask.charAt (i) == UPPERCASE || mask.charAt (i) == '_') { found = true; break; } // Throw an IllegalArgumentException object if no mask // characters were found. if (!found) throw new IllegalArgumentException ("No mask characters found"); // Save the mask. this.mask = mask; // Allow keystroke events to reach this component's overridden // processKeyEvent method. enableEvents (AWTEvent.KEY_EVENT_MASK); // Register a FocusListener so that we can perform validation // (if the validate field is set to true). addFocusListener (new FocusAdapter () { // ====================================== // FocusLost is called when the component // loses focus. // ====================================== public void focusLost (FocusEvent e) { // If we are not validating or the // field contains no input data, allow // focus change to proceed. if (!validate || index == startIndex) return; // index equals lastIndex when all // entry positions have been filled. // If index is less than or equal to // lastIndex, we have not filled all of // these positions so we must prevent // focus from remaining with the next // focusable component. In other // words, keep the focus in the current // component until all entry positions // have been filled. if (index <= lastIndex) requestFocus (); return; } }); } // ============================================================== // void addNotify () // // Create the component's peer - the native window that displays // the component. // ============================================================== public void addNotify () { // Create the peer. super.addNotify (); // Create a copy of the mask. StringBuffer mask2 = new StringBuffer (mask); // Change all mask codes to underscore characters. These // characters identify the entry positions on the screen. for (int i = 0; i < len; i++) if (mask2.charAt (i) == ANYCHAR || mask2.charAt (i) == DIGIT || mask2.charAt (i) == LOWERCASE || mask2.charAt (i) == UPPERCASE) mask2.setCharAt (i, '_'); // Display the mask. This is not legal until the peer is // visible on the screen - which was accomplished by calling // super.addNotify. String s = mask2.toString (); setText (s); // Calculate and save the first entry position index. startIndex = index = s.indexOf ('_'); // Set the displayed caret to this position. setCaretPosition (startIndex); // Calculate and save the last entry position index. lastIndex = s.lastIndexOf ('_'); } // ================================================= // String getData () // // Return only the entered data. // // Return: // // entered data or null if there is no entered data. // ================================================= String getData () { // Get the text. String text = getText (); // If no text was entered, there is no entered data. Therefore, // return null. if (text == null || text.length () != len) return null; // Create a buffer for appending entered data characters. StringBuffer sb = new StringBuffer (); // Append all entered data to the buffer. Entered data consists // of characters typed in mask positions c, 9, a, A, or _. for (int i = 0; i < index; i++) if (mask.charAt (i) == ANYCHAR || mask.charAt (i) == DIGIT || mask.charAt (i) == LOWERCASE || mask.charAt (i) == UPPERCASE || mask.charAt (i) == '_') sb.append (text.charAt (i)); // Return the contents of the buffer, after converting to a // String. return sb.toString (); } // ============================================================== // void processKeyEvent (KeyEvent e) // // Arguments: // // e - reference to KeyEvent object that holds information // regarding a key pressed, key released, or key typed event. // ============================================================== protected void processKeyEvent (KeyEvent e) { // If a key pressed event is detected ... if (e.getID () == KeyEvent.KEY_PRESSED) { // If the Backspace key was pressed ... if (e.getKeyCode () == KeyEvent.VK_BACK_SPACE) { // A zero index value means the flashing caret indicator // is in the leftmost entry position. This assumes that // the first mask character is c, 9, a, A, or _. // If the index is zero, discard the event because it is // meaningless to backspace past the first position. if (index == 0) { e.consume (); return; } // Decrement index by one. This is done so that index // contains the position of the rightmost entered // character. (Normally, index contains the next entry // position - one position past the rightmost entered // character.) index--; // Place the displayed text into a buffer. StringBuffer sb = new StringBuffer (getText ()); // Rub out the leftmost entered character. do { // If the buffer character matches the mask character // then we must skip over the mask character. For // example, if the mask is (a)a, we don't want to // rub out the ( or ) characters since they must be // displayed regardless of any character entry. if (sb.charAt (index) == mask.charAt (index)) index--; else { // Rub out the rightmost character by replacing // it with an underscore character. sb.setCharAt (index, '_'); setText (sb.toString ()); // We can now terminate the loop because we only // rub out one character at a time. break; } } while (index >= 0); // index is less than zero if we encountered something // like ( in the leftmost position. If this is the // case, we must set index back to the first entry // position. if (index < 0) index = startIndex; // Don't forget to update the caret position. setCaretPosition (index); } } // If a key pressed event or a key released event is detected // ... if (e.getID () == KeyEvent.KEY_PRESSED || e.getID () == KeyEvent.KEY_RELEASED) { int keyCode = e.getKeyCode (); if (keyCode == KeyEvent.VK_BACK_SPACE || keyCode == KeyEvent.VK_DELETE || keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_END || keyCode == KeyEvent.VK_HOME || keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_UP) { // Discard the event (so that keystroke does not reach // the component) and exit this handler. e.consume (); return; } // Pass keystroke to component and exit handler. super.processKeyEvent (e); return; } // If a key typed event is detected ... if (e.getID () == KeyEvent.KEY_TYPED) { // Discard the key typed event if either a backspace // character has been detected or the maximum number of // characters has been entered. if (e.getKeyChar () == '\b' || index == len) { e.consume (); return; } // Based on the mask character for the current entry // position, make sure only appropriate character will be // accepted. switch (mask.charAt (index)) { case DIGIT: if (!Character.isDigit (e.getKeyChar ())) { e.consume (); return; } break; case LOWERCASE: if (!Character.isLowerCase (e.getKeyChar ())) { e.consume (); return; } break; case UPPERCASE: if (!Character.isUpperCase (e.getKeyChar ())) { e.consume (); return; } } // Save the typed character and advance the entry position. StringBuffer text = new StringBuffer (getText ()); text.setCharAt (index++, e.getKeyChar ()); // Display the typed character. setText (text.toString ()); // Advance the caret position to the next entry position. setCaretPosition (index); while (index < len) if (text.charAt (index) == '_') { setCaretPosition (index); break; } else index++; // Discard the key typed event. e.consume (); } } }
The most important thing about FormattedTextField is the call to enableEvents in the constructor, along with the processKeyEvent method override. Collectively, these tasks ensure all keystrokes pass through to processKeyEvent before being sent to the native window that displays and manages the text field.
processKeyEvent is called with a KeyEvent argument that describes one of three eventspressed, typed, or released. A pressed event occurs when the user presses a key on the keyboard. A typed event occurs when the user presses a key that represents a character (such as A or Backspace). Finally, a released event occurs when the user releases a key. If the user presses a key associated with a character, KeyEvent's getKeyChar method returns that character. However, if the user presses a key associated with a non-character (such as the left-arrow key), KeyEvent's getKeyCode method returns that non-character.
processKeyEvent can prevent a KeyEvent from reaching FormattedTextField's peer (the platform-specific native window that displays a component and controls its operation) by calling KeyEvent's consume method. Why is this done? A KeyEvent is consumed to prevent a displayable character, represented by this event, from reaching the peer and being displayed. Furthermore, certain control keystrokes (such as a Delete keystroke) should not be allowed to reach the peer because they would "screw up" the logic in processKeyEvent.
To demonstrate FormattedTextField, I've created an application called UseFormattedTextField. This application's source code is presented in Listing 6.
Listing 6 The UseFormattedTextField application source code
// UseFormattedTextField.java import java.awt.*; import java.awt.event.*; class UseFormattedTextField extends Frame implements ActionListener { TextArea ta; FormattedTextField ftfDate, ftfName, ftfAddress, ftfPhone, ftfSalary; UseFormattedTextField (String title) { // Pass the title to the Frame layer so that this title can // appear in the title bar. super (title); // Establish a window listener so that we can exit the program // if either the System Close menu item is selected or the X // button is pressed. addWindowListener (new WindowAdapter () { public void windowClosing (WindowEvent e) { System.exit (0); } }); // Construct the GUI. // 1. Establish default background and foreground colors. setBackground (Color.blue); setForeground (Color.white); // 2. Set the Frame's layout to a BorderLayout with no // horizontal gaps and 10-pixel gaps between the North, Center, // and South regions. setLayout (new BorderLayout (0, 10)); // 3. Create Panel for North region and set its layout manager // to BorderLayout. Panel p = new Panel (); p.setLayout (new BorderLayout ()); // 4. Create the West portion of the North Panel and assign it a // GridLayout layout manager divided into five rows by 1 // column, no horizontal gaps, and 5-pixel gaps between rows. Panel p1 = new Panel (); p1.setLayout (new GridLayout (5, 1, 0, 5)); // 5. Add five labels to the West Panel. p1.add (new Label ("Date (mm/dd/yyyy):")); p1.add (new Label ("Name:")); p1.add (new Label ("Address:")); p1.add (new Label ("Phone:")); p1.add (new Label ("Salary:")); // 6. Add the West Panel to the North region Panel. p.add (p1, BorderLayout.WEST); // 7. Create the East portion of the North Panel and assign it a // GridLayout layout manager divided into five rows by 1 // column, no horizontal gaps, and 5-pixel gaps between rows. p1 = new Panel (); p1.setLayout (new GridLayout (5, 1, 0, 5)); // 8. Create a FormattedTextField for entering the date. // Override the default foreground color and add to the East // Panel. ftfDate = new FormattedTextField ("99/99/9999", 10, true); ftfDate.setForeground (Color.black); p1.add (ftfDate); // 9. Create a FormattedTextField for entering the name. // Override the default foreground color and add to the East // Panel. ftfName = new FormattedTextField ("ccccccccccccccccccccccccc", 25, false); ftfName.setForeground (Color.black); p1.add (ftfName); // 10. Create a FormattedTextField for entering the address. // Override the default foreground color and add to the East // Panel. ftfAddress = new FormattedTextField ("____________________", 25, false); ftfAddress.setForeground (Color.black); p1.add (ftfAddress); // 11. Create a FormattedTextField for entering the phone // number. Override the default foreground color and add to // the East Panel. ftfPhone = new FormattedTextField ("(999) 999-9999", 15, true); ftfPhone.setForeground (Color.black); p1.add (ftfPhone); // 12. Create a FormattedTextField for entering the salary. // Override the default foreground color and add to the East // Panel. ftfSalary = new FormattedTextField ("99,999.99", 10, true); ftfSalary.setForeground (Color.black); p1.add (ftfSalary); // 13. Add the East Panel to the North region Panel. p.add (p1, BorderLayout.EAST); // 14. Add the North region Panel to the North region of the // Frame window. add (p, BorderLayout.NORTH); // 15. Create a 5 row by 25 column TextArea and override the // default foreground color. ta = new TextArea (5, 25); ta.setForeground (Color.black); // 16. Add the TextArea to the Center region of the Frame // window. add (ta); // 17. Create Panel for South region and set its layout manager // to a centered FlowLayout with no gaps. p = new Panel (); p.setLayout (new FlowLayout (FlowLayout.CENTER, 0, 0)); // 18. Create a Button, override its default foreground color, // and register the current UseFormattedTextField object as // a listener for Action events originating from this // component. Button b = new Button ("Get Data"); b.setForeground (Color.black); b.addActionListener (this); // 19. Add the Button to the South Panel. p.add (b); // 20. Add the South region Panel to the South region of the // Frame window. add (p, BorderLayout.SOUTH); // 21. Set the Frame window size to 350 by 350 pixels. setSize (350, 350); // 22. Do not allow the user to resize the Frame window. setResizable (false); // 23. Show the Frame window. setVisible (true); } public void actionPerformed (ActionEvent e) { // Create a buffer for holding raw entry data. StringBuffer sb = new StringBuffer (); // Append all raw entry data to the buffer. sb.append ("Date: " + ftfDate.getData () + "\n"); sb.append ("Name: " + ftfName.getData () + "\n"); sb.append ("Address: " + ftfAddress.getData () + "\n"); sb.append ("Phone: " + ftfPhone.getData () + "\n"); sb.append ("Salary: " + ftfSalary.getData () + "\n"); // Convert the buffer to a String and place its contents in the // TextArea. ta.setText (sb.toString ()); } // Establish a border area around the components and Frame edges. // The Frame container's layout manager calls this method. public Insets getInsets () { return new Insets (35, 15, 15, 15); } public static void main (String [] args) { new UseFormattedTextField ("Use Formatted Text Field"); } }
UseFormattedTextField creates a GUI consisting of several labels, matching FormattedTextFields, a TextArea, and a Button labeled Get Data. After data has been entered into these text fields, pressing the Get Data button causes an action event to be fired, resulting in a call to UseFormattedTextField's actionPerformed method. In turn, actionPerformed calls each FormattedTextField object's getData method. This method returns all characters that the user entered into a formatted text field. The results of all getData method calls are concatenated into a String object and the contents of this object appear in the TextArea. The GUI, sample input, and result of pressing the Get Data button appear in Figure 5.
UseFormattedTextField demonstrates several FormattedTextField components.
Sun has reported a number of enhancements to its Swing API in the SDK 1.4 release of Java (expected in late 2001). One of these enhancements is a new Swing component that supports formatted text entry. However, it's doubtful that Sun will offer the same kind of support in a new AWT component. Therefore, if you haven't yet migrated to Swing and need formatted text entry, consider using FormattedTextEntry for your formatted text-entry needs.
As an exercise, try modifying FormattedTextEntry to support new mask characters X and x for entering hexadecimal characters. For example, X allows entry of hexadecimal characters AF and 09, whereas x allows entry of hexadecimal characters af and 09.