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 “`~!@#$%^&*()_+=\|”‘:;?/>.<, ". It allows a minus signonly if it is the first character entered, to signify a negativevalue.

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        = "`~!@#$%^&*()_+=\|"':;?/>.<, ";    public void processKeyEvent(KeyEvent ev) {        char c = ev.getKeyChar();        if((Character.isLetter(c) && !ev.isAltDown())            || badchars.indexOf(c) > -1) {            ev.consume();            return;        }        if(c == '-' && getDocument().getLength() > 0) ev.consume();        else super.processKeyEvent(ev);    }} -1) {            ev.consume();            return;        }        if(c == '-' && getDocument().getLength() > 0) ev.consume();        else super.processKeyEvent(ev);    }}
See also  Essential Measures for Safeguarding Your Digital Data

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist