0

I'm trying to create a method that only allows me to type a single number into a text field however my current code does not work. It allows me to type letters in even though the KeyPressed method is triggered. The code that only restricts the input to 1 character works however.

void formatTextField(JTextField field)
{
    field.addKeyListener(new KeyAdapter()
    {
        public void keyTyped(KeyEvent e)
        { 
            if (field.getText().length() >= 1)
            {
                e.consume();
            }
        }
        public void keyPressed(KeyEvent e)
        {               
            try
            {
                String keyText = KeyEvent.getKeyText(e.getKeyCode());
                Integer.parseInt(keyText);
            }
            catch(NumberFormatException | NullPointerException ex)
            {
                e.consume();
            }
        }
    });
}
2
  • Why do you use two different event methods instead of just one? Commented Oct 13, 2019 at 15:21
  • Some sort of lapse in judgement told me it would be necessary for what I was trying to do. It wasn't the right call you're right. Commented Oct 13, 2019 at 15:39

1 Answer 1

2

It would be better if you use an already existing solution for such cases. You can use JFormattedTextField or a JSpinner. There is no need to spend time/effort to create KeyListeners or some kind of filter.

Plus a JSpinner is more user friendly since user is able to recognize that this field accepts only numbers.

If you insist of using JTextField, I suggest you to take the DocumentFilter approach, mostly described in this question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.