Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow introducing only digits in jTextField?

I have tried to use the example shown here but java showing error message of

"AttributeSet cannot be resolved to a type"

That is why I am trying to use another method of allowing only digits:

txtUsername.addKeyListener(new MyKeyListener());

public class MyKeyListener extends KeyAdapter{
  public void keyPressed(KeyEvent ke){
      System.out.println("Key pressed code = "+ke.getKeyCode());
      if (ke.getKeyCode()>=48 && ke.getKeyCode()<=57)
              return true;
      else
              return false;
  }
} 

But of course it is not working because keyPressed method is void. So, what to do in order to print only digits in textfield?

like image 590
Bakhtiyor Avatar asked Feb 28 '12 06:02

Bakhtiyor


1 Answers

My version which rejects unwanted characters completely(I tried):

        val2 = new JTextField();
        val2.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {

            try {

                char input = e.getKeyChar(); //checks each key pressed
                // in other words it prevents input of any character other than 0-9 or .

                try {
                    int i = Integer.parseInt(val2.getText());
                    valid1.setText(""); //valid1 is a label for the message

                } catch (Exception e2) {
                    // TODO: handle exception
                    valid1.setText("Invalid Number!");
                }

                if((!Character.isDigit(input)) && !(input == '.')) { //numbers accept "."
                    e.consume();
                    // event won't be sent for any further event listeners
                    try {
                        int i = Integer.parseInt(val2.getText()); // checks if the string can be converted to int
                        double i1 = Double.parseDouble(val2.getText()); // checks if string can be converted to double
                        valid1.setText("");

                    } catch (Exception e2) {
                        // TODO: handle exception
                        // if it is not in a valid format.. it will generate error message
                        valid1.setText("Invalid Number!");
                    }


                }
                else {
                    // if format and characters are fine... no output
                    valid1.setText("");
                }


            }
            catch (Exception e2) {
                // TODO: handle exception
                // for unexpected errors
                valid1.setText("Error");
            }

        }

    });

    // auto generated for design of the textfield
    val2.setColumns(10);
    val2.setBounds(236, 11, 126, 43);
    panel.add(val2);
like image 123
Baboolull Yougesh Avatar answered Sep 28 '22 06:09

Baboolull Yougesh