Share this page 

Limit TextField input to numeric valueTag(s): AWT


[JDK1.0.2]
//   You still have to trap the InvalidNumberFormat 
//   Exception when converting textfield content to numeric
//   bug fixed! 980211 thanks to JM Guerra Chapa
import java.awt.*;
public class app extends java.applet.Applet {
  TextField textField1;

  public void init() {
    setLayout(new FlowLayout());
    textField1 = new TextField(10);
    add(textField1);
    }

  public boolean handleEvent(Event event) {
     if (event.target==textfield1 && event.id == Event.KEY_PRESS) {
       char c = (char)event.key;
       if (c >= '0' && c <= '9') {
         // keep digit
         return super.handleEvent(event);
         } 
       else if (Character.isISOControl(c)) {
         // keep control character (like del, bksp)
         return super.handleEvent(event);
         } 
       else {
         // discard Character
         return true;
         }
       }
     return super.handleEvent(event);
     }
}
[JDK1.1]
thanks to Lionel Giltay
import java.awt.TextField ;
import java.awt.event.KeyAdapter ;
import java.awt.event.KeyEvent ;
 
public class NumericTextField extends TextField
{
 public NumericTextField (String _initialStr, int _col)
 { 
    super (_initialStr, _col) ;
       
    this.addKeyListener(new KeyAdapter()
   {
       public void keyTyped (KeyEvent e) 
        { 
            char c = e.getKeyChar() ;
                
            if (!   ((c==KeyEvent.VK_BACK_SPACE) || (c==KeyEvent.VK_DELETE) 
                ||  (c== KeyEvent.VK_ENTER)      || (c == KeyEvent.VK_TAB) 
                ||  (Character.isDigit(c)))) 
            {
               e.consume() ;
           } 
        } 
    });
 } 
        
  public NumericTextField (int _col) 
  { 
    this ("", _col) ; 
  } 
}