RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Expertise: Beginner
Sep 26, 2000

Creating a Numeric-Input JTextField

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

The IntegerTextField class below is a simple example that only allows a user to enter positive or negative integer values. It consumes any KeyEvents for letters, unless the ALT key is pressed, in which case the event may be needed to activate JButton mnemonics. It also consumes all whitespace and punctuation-type characters contained in the String "`~!@#$%^&*()_+=\\|\"':;?/>.<, ". It allows a minus sign only if it is the first character entered, to signify a negative value.

This class could easily be enhanced, perhaps to allow the entry of floating-point numbers or restrict input to non-negative values. The basic idea, however, is the same: Process the allowable KeyEvents, and consume 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) {
        if(c == '-' && getDocument().getLength() > 0) 
        else super.processKeyEvent(ev);


David Glasser
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date