Creating a Numeric-Input JTextField

Creating a Numeric-Input JTextField

Validating user input that is typed into a JTextField can becumbersome, especially if the input string must be converted to anumeric value such as an int. By subclassing JTextField, however, andoverriding its processKeyEvent() method, (which was added in Java 1.2)it is very easy to control which types of characters may or may not betyped into the field.

The IntegerTextField class below is a simple example that only allowsa user to enter positive or negative integer values. It consumes anyKeyEvents for letters, unless the ALT key is pressed, in which casethe event may be needed to activate JButton mnemonics. It alsoconsumes all whitespace and punctuation-type characters contained inthe String “`~!@#$%^&*()_+=\|”‘:;?/>.This class could easily be enhanced, perhaps to allow the entry offloating-point numbers or restrict input to non-negative values. Thebasic idea, however, is the same: Process the allowable KeyEvents, andconsume the rest.

 import java.awt.event.KeyEvent;import javax.swing.JTextField;public class IntegerTextField extends JTextField {    final static String badchars        = "`~!@#$%^&*()_+=\|"':;?/>. -1) {            ev.consume();            return;        }        if(c == '-' && getDocument().getLength() > 0) ev.consume();        else super.processKeyEvent(ev);    }}


Share the Post: