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();
            }
        }
    });
}
Edd
  • 136
  • 9
  • Why do you use two different event methods instead of just one? – Tom Oct 13 '19 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. – Edd Oct 13 '19 at 15:39

1 Answers1

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.

George Z.
  • 6,643
  • 4
  • 27
  • 47