1

I want to filter the key that are pressed on JTextField. I want that only numbers are allowed, and if other character are pressed it remove it or don't allow the storage on the text field.

I'm thinking to use an addKeyListener, and use the methods: key pressed and key released.

Any Ideas?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
MatroxDev
  • 49
  • 8
  • Possible duplicate: http://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers – Alex Feb 02 '13 at 12:09
  • *"I want that only numbers are allowed"* Use a `JSpinner` with a `SpinnerNumberModel` as seen in [this answer](http://stackoverflow.com/a/9345991/418556). – Andrew Thompson Feb 03 '13 at 03:59

3 Answers3

1

Try this

final JTextField myTextField = new JTextField();
myTextField.addKeyListener(new KeyListener() {
      String oldText = "";
      public void keyPressed(KeyEvent keyEvent) {
                // Store old text in a temporary variable
                oldText = myTextField.getText();
      }

      public void keyReleased(KeyEvent keyEvent) {
                 // Make sure that the user is typing a number else replace with old text.
                 int charCode = (int)keyEvent.getKeyChar();
                 if (charCode  < 48 || charCode  > 57){
                     myTextField.setText(oldText); // Replace with old text.
                 }
      }

      public void keyTyped(KeyEvent keyEvent) {
      }
    });
Ravindra Gullapalli
  • 9,049
  • 3
  • 48
  • 70
1

No offence, Mr. Ravindra's answer is correct but it fails when you type continuously .. I hope this helps :

    final JTextField myTextFiled=new JTextField();
    JFrame frame=new JFrame("onlyNums");
    KeyListener myKeyListner=new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            // TODO Auto-generated method stub
            if(e.getKeyChar()>='0' && e.getKeyChar()<='9')                  
                myTextFiled.setText(myTextFiled.getText()+e.getKeyChar());
            else if(e.getKeyChar()==KeyEvent.VK_BACK_SPACE && myTextFiled.getText().length()>0)
                myTextFiled.setText(myTextFiled.getText().substring(0, myTextFiled.getText().length()-1));
        }

        @Override
        public void keyReleased(KeyEvent e) {
            // TODO Auto-generated method stub              
        }

        @Override
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub              
        }
    };
    //to null out handling other inputs
    myTextFiled.setInputMap(JTextField.WHEN_FOCUSED, new InputMap());
    //to add your own handling
    myTextFiled.addKeyListener(myKeyListner);

Note: You have to add handling to insert/remove from the pointer's position.

Regards,

CME64
  • 1,673
  • 13
  • 24
0

Use a custom Document:

public class NumericDocument extends PlainDocument {

    @Override
    public void insertString(int pos, String text, AttributeSet as)
                                               throws BadLocationException {
        try {
            Integer.parseInt(text);
            super.insertString(pos, text, as);
        } catch(NumberFormatException e) {
            Toolkit.getDefaultToolkit().beep();
        }
    }

}

Install to your TextField:

JtextField field = new JTextField();
field.setDocument(new NumericDocument());

This will work, even if text is pasted (where no KeyEvent is fired).

Mordechai
  • 15,437
  • 2
  • 41
  • 82