• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 179
  • Last Modified:

how to detect input is char but not no.

hello.......

i have a text input but i would like user enter no. only but not char/words........so how to write the code

thanks
0
bhuey_ling
Asked:
bhuey_ling
1 Solution
 
expertmbCommented:
hi,
try this

    jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {

      public void keyPressed(KeyEvent e) {

     int iKeyCode=e.getKeyCode();
    String sLength = jTextField1.getText();
    if((sLength.length()>12)&&(iKeyCode!=e.VK_BACK_SPACE)&&(iKeyCode!=e.VK_DELETE)){
        jTextField1.setEditable(false);
    }
    else if(iKeyCode == e.VK_ENTER){
      jTextField1.setEditable(true);
    }
    else if(isChar(e.getKeyChar())){
      jTextField1.setEditable(false);
    }
    else{
      jTextField1.setEditable(true);
   }

      }

      public void keyReleased(KeyEvent e) {
    jTextField1.setEditable(true);

      }
    });

  public boolean isChar(char ch){

   char[] oChar ={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o',
   'p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H',
   'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','~',
   '`','!','@','#','$','%','^','&','*','(',')','_','-','+','=','{','[','}','}',
   '|','\\',':',';','"','\'','<',',','>','.','?','/'};
   for(int iCount =0;iCount<oChar.length;iCount++){
     if(ch==oChar[iCount]){
       return true;
     }
   }
   return false;
 }


mb...
0
 
vivexpCommented:
Hi,

This is what  i tried out to input only nos. Probably u have to modify a little bit.

JTextField jtf;
static String s1;

jtf.addKeyListener(new java.awt.event.KeyAdapter() {

      public void keyPressed(KeyEvent e) {
        jtf_keyPressed(e);
      }

      public void keyReleased(KeyEvent e) {
        jtf_keyReleased(e);
      }
    });


Methods.....
 void jtf_keyPressed(KeyEvent e) {
   System.out.println (""+e.getKeyCode ());
    if(e.getKeyCode ()<=65){
    s1=s1+String.valueOf (e.getKeyChar ());
      jtf.setText (s1);
   }
   else
      jtf.setText (" ");
  }

  void jtf_keyReleased(KeyEvent e) {
  if(e.getKeyCode ()>=65) {
      jtf.setText (" ");
      s1="";
  }
  }

Try out...
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now