0

How do I create a JFormattedTextField that only takes in a set of numbers and will not allow the user to type in letters or any other characters besides 0123456789?

1
  • DocumentFilter, but NumberFormatter seems like as good for ... (accepts decimal separator)
    – mKorbel
    Dec 31, 2015 at 17:34

1 Answer 1

1

for this you have to create your custom KeyListener following code will show you how you can achieve this

JFormattedTextField textField = new JFormattedTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub
        char c = e.getKeyChar();

        if(!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE)) {
            Toolkit.getDefaultToolkit().beep();
            e.consume();
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.