1

Trying to make the text field accept only integers

some how it either consumes everything I type in the field or it just lets to type anything it's simple that's why its hard to find the problem.

JLabel year = new JLabel("Year:");
      final JTextField yeart = new JTextField(10);
      yeart.addKeyListener(new KeyAdapter()
      {
         @Override
         public void keyTyped(KeyEvent e)
         {
            super.keyTyped(e);

            e.getKeyCode();

            if (!(e.getKeyCode() >= 48 || e.getKeyCode() <= 57))
            {
               e.consume();
            }
         }



      });
FancyPants
  • 93
  • 1
  • 4
  • 20
  • In future, please add the programming language you are using as a tag to your questions, this will help more people to find your questions, which will help get them answered faster. – Robin Green Nov 30 '13 at 13:11
  • 1
    Posting an [SCCEE](http://sccee.org) will get you better results. – Paul Samsotha Nov 30 '13 at 13:13
  • 1
    Use a `DocumentListener` or `DocumentFilter` when working with `JTextComponent` instances, and not a `KeyListener`. For example copy-paste will mess up your functionality. Besides that, you can use a `JFormattedTextField` for this as well (see [here](http://stackoverflow.com/a/13424140/1076463) for an example) – Robin Nov 30 '13 at 13:24
  • Why would i use DocumentListenet or DocumentFilter if i can make this work? this is way more simpler to understand and explain. – FancyPants Nov 30 '13 at 13:27
  • @FancyPants _if I can make this work_. I am saying you cannot: for example copy-paste or drag-and-drop will not work with your `KeyListener` – Robin Nov 30 '13 at 13:32
  • @Robin made it work. It's not something fancy and high leveled that I'm doing. My program is just to create bookings for a car rental company. At the moment I don't need those extra features that DocumentListener and DocumentFilter offer. – FancyPants Nov 30 '13 at 13:50
  • `At the moment I don't need those extra features that DocumentListener and DocumentFilter offer` - You would not use a DocumentListener, only a DocumentFilter. Using a filter is NOT an extra feature, it is one of the few ways to get you code working properly, as Robin has already told you. Try pasting the string "abc" into your text field. – camickr Nov 30 '13 at 16:36

1 Answers1

1

Use && instead ||. (!(e.getKeyCode() >= 48 || e.getKeyCode() <= 57)) will simply return false for every input.

BK Prajapati
  • 38
  • 2
  • 7