-1

I am trying to create a GUI project and I want my textfield to only accept digits and backspace. I am currently new to Java so I don't have a lot of knowledge about it yet.

Here's my code so far:

AgeField = new JTextField();
AgeField.addKeyListener(new KeyAdapter(){
   public void keyPressed(KeyEvent ke) {
      String value = AgeField.getText();
      int l = value.length();
      if (ke.getKeyChar() >= '0' && ke.getKeyChar() <= '9' && ke.getKeyChar() == KeyEvent.VK_BACK_SPACE) {
           AgeField.setEditable(true);
      }
      else {
           AgeField.setEditable(false);
      }
   }
});

My current code only accepts digits, however, when the user enters a letter the textfield becomes uneditable and he cannot enter a digit or delete the letter that he entered.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Richard
  • 27
  • 1
  • 6
  • I suggest either [JFormattedTextField](https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html) or [DocumentFilter](https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) – Abra Mar 16 '21 at 16:52
  • Does this answer your question? [Restricting JTextField input to Integers](https://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers) – Abra Mar 16 '21 at 16:56
  • Also consider using a `JSpinner` with a `SpinnerNumberModel`. It doesn't work exactly as you describe, but the user might prefer it. – Andrew Thompson Mar 16 '21 at 19:26

1 Answers1

0

You should apply this change:

if ((ke.getKeyChar() >= '0' && ke.getKeyChar() <= '9') || (ke.getKeyChar() == KeyEvent.VK_BACK_SPACE))

but you can also do better process instead setEditable(false); for example: you can remove last character.

Peyman128
  • 1
  • 1
  • Actually, you shouldn't use a `KeyListener`. You can still "paste" non-digit characters into the `JTextField`. That's why `DocumentFilter` class exists. – Abra Mar 17 '21 at 03:20