0

I'm trying to validate a jtextbox so that it will only except numbers, full stops, backspace and enter.

This is the code that i have come up with reading up on KeyEvent class, but when i test the text box it will still let me type the letter "n" any help and or direction on this issue would be greatly appreciated. (Note - all other events are consumed.)

private void fastPassExtraKeyTyped(java.awt.event.KeyEvent evt) {                                       
    char c = evt.getKeyChar(); // on key press event, gets the character used

    // sets what is valid, if NOT one of these described, then consume event and play sound
    if (!(Character.isDigit(c) || (c == KeyEvent.VK_PERIOD) || (c == KeyEvent.VK_DECIMAL) || (c == KeyEvent.VK_BACKSPACE) || (c == KeyEvent.VK_DELETE))) 
    {
        getToolkit().beep(); // sound made if wrong button pressed to alert user
        evt.consume();// key press will be consumed
    }

this is also my first post to stackoverflow iv mainly been lurking in the background reading up on issues that i have come across and not had to ask questions as they have already been answered

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Without your [mcve], a small running program posted with your question, it's hard to know exactly what you're doing wrong, other than you should not be adding a KeyListener to a JTextField. Instead use the appropriate tool, here by adding a DocumentFilter to the JTextField's Document. – Hovercraft Full Of Eels Mar 15 '18 at 14:23
  • [For example](https://stackoverflow.com/questions/19063377/issue-with-implementation-of-keylistener-for-writting-unicode-sindhi-in-java/19063419#19063419) (and a possible duplicate) – Hovercraft Full Of Eels Mar 15 '18 at 14:24
  • 1
    You should do it with documents, as described [here](https://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers) – BackSlash Mar 15 '18 at 14:25
  • thank you for the direction! – Michael Briggs Mar 15 '18 at 14:25
  • Great answer to those questions (LOL) – Hovercraft Full Of Eels Mar 15 '18 at 14:28
  • `I'm trying to validate a jtextbox so that it will only except numbers, full stops, backspace and enter.` - First of all use proper class names. Its `JTextField`. But the solution is to use a `JFormattedTextField` which allows you to specify a mask for numeric values. See: [How to Use Formatted Text Fields](https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html). – camickr Mar 15 '18 at 14:51

0 Answers0