Chromatica
Chromatica

Reputation: 123

Setting JFormattedTextField to take only allowed values

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?

Upvotes: 0

Views: 73

Answers (1)

Usman Naseer
Usman Naseer

Reputation: 60

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();
        }
    }

Upvotes: 1

Related Questions