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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Expertise: Beginner
Sep 26, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



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