We help IT Professionals succeed at work.

textfield that accepts numbers only???

rdy1437
rdy1437 asked
on
Medium Priority
494 Views
Last Modified: 2012-08-13
i would like for my textfield to accept only numbers(it will also accept -, . ex: -12.00)? how will i do it??


raymond
Comment
Watch Question

Commented:
what kind of text field is this ? a html form element ?

Commented:
Hi rdy :)

Sorry for recycling my previous answer to your other TextField question, but you can change class name and the rest you don't like ;)

-------8<---------------------cut-here-------
import java.awt.*;
import java.awt.event.*;

public class LimitedTextField2 extends TextField implements TextListener
{
    // Constants
    public static final int BYTE = 0;
    public static final int SHORT = 1;
    public static final int INTEGER = 2;
    public static final int LONG = 3;
    public static final int FLOAT = 4;
    public static final int DOUBLE = 5;
   
    // Properties
    private int type;
   
    private String oldValue;
    private int oldCaretPosition;
   
    // Constructors
    public LimitedTextField2( int type )
    {
        super();
        this.type = type;
       
        oldValue = getText();
        oldCaretPosition = getCaretPosition();
       
        addTextListener( this );
    }
   
    // Methods
    private boolean isValidNumber( String number )
    {
        if ("".equals( number ) || "-".equals( number ) || "+".equals( number ))
        {
            return true;
        }
       
        try
        {
            if (type==BYTE)
            {
                Byte.parseByte( number );
                return true;
            }
           
            if (type==SHORT)
            {
                Short.parseShort( number );
                return true;
            }
           
            if (type==INTEGER)
            {
                Integer.parseInt( number );
                return true;
            }
           
            if (type==LONG)
            {
                Long.parseLong( number );
                return true;
            }
           
            if (type==FLOAT)
            {
                Float.parseFloat( number );
                return true;
            }
           
            if (type==DOUBLE)
            {
                Double.parseDouble( number );
                return true;
            }
           
            return false;
        }
        catch( NumberFormatException nfe )
        {
            return false;
        }
    }
   
    // TextListener interface
    public void textValueChanged( TextEvent e )
    {
        Object source = e.getSource();
       
        if (source==this)
        {
            String newValue = getText();
            int newCaretPosition = getCaretPosition();
           
            if (!isValidNumber( newValue ))
            {
                setText( oldValue );
                setCaretPosition( oldCaretPosition );
            }
            else
            {
                oldValue = newValue;
                oldCaretPosition = newCaretPosition;
            }
        }
    }
   
} /* LimitedTextField2 */
-------8<---------------------cut-here-------

With this class you can create an instance like this:

    new LimitedTextField2( LimitedTextField2.FLOAT )

...or any of the enumerated constants in the class.

Cheers,
    </ntr> :)
A more efficient approach to check each character is as follows:

private static BitSet bs = new BitSet(11);

static {
bs.set('0');
bs.set('1');
bs.set('2');
bs.set('3');
bs.set('4');
bs.set('5');
bs.set('6');
bs.set('7');
bs.set('8');
bs.set('9');
bs.set('-');
}

To chack any given character:

boolean bIsOK = bs.get(charToCheck);

Commented:
The new Java 1.4 release supports field edit masks that does all the work for you...
Commented:
thanks guys!!!

but i found a way to solve this....here's my code:

import java.awt.*;
import java.awt.event.*;

public class NumberField extends TextField
{

     public NumberField()
     {
          addKeyListener(new KeyAdapter()
          {
               public void keyTyped(KeyEvent ke)
               {
                    char c = ke.getKeyChar();

                    if((!(Character.isDigit(c))) &&  (c !='\b') && ( c != '-') && (c != '.')) // For backspace
                    //if(!Character.isDigit(c))
                    {
                       ke.consume();
                       System.out.println(c);

                    }


                    //System.out.println(ke.getKeyChar());

               }
          });

     }


     public static void main(String args[])
     {
          Frame f = new Frame("this is a frame");
          f.setVisible(true);
          f.pack();

          f.add(new NumberField());
     }
}
That works too.
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- To be PAQ'ed and points refunded

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer

Explore More ContentExplore courses, solutions, and other research materials related to this topic.