Question

I want to make the text field only accept numeric and backspace button from the user.

I have added the function that use to check the keycode from the user, but I don't know how to stop the key press event if the keycode is not numeric.

What code do I need to add into the function to stop the event??

 private void jTextField2KeyPressed(java.awt.event.KeyEvent evt)   
 {                                       

   if(!((evt.getKeyCode()==8) || (evt.getKeyCode()>48 && evt.getKeyCode()<57)))
   {
      //how to stop the key pressed event
   }
 }
Was it helpful?

Solution

You don't need to mess with the Swing event handling to achieve this.

The best way is to use a JFormattedTextField instead.

See the Java tutorial for details:

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

OTHER TIPS

Try overriding keyTyped:

@Override
public void keyTyped(KeyEvent evt) {
    if (!Character.isDigit(evt.getKeyChar()) && !(evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)) {
        evt.consume();
    }
}

Update:

In case you want pasting to not work and enforce the input to be typed, you can use the following.

@Override
public void keyPressed(KeyEvent evt) {
    if(evt.isControlDown() && evt.getKeyCode() == KeyEvent.VK_V) {
        evt.consume();
    }
}

set the DocumentFilter of the PlainDocument of the text field.
Sample:

    PlainDocument document = new PlainDocument();
    document.setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs) throws BadLocationException {
            fb.insertString(offset, filter(text), attrs);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            fb.replace(offset, length, filter(text), attrs);
        }

        private String filter(String text) {
            StringBuilder builder = new StringBuilder(text);
            for (int i = 0; i < builder.length();) {
                if (Character.isDigit(builder.charAt(i))) {
                    i += 1;
                } else {
                    builder.deleteCharAt(i);
                }
            }
            return builder.toString();
        }
    });

    JTextField field = new JTextField(document, null, 0);

I would suggest that you see if you can consume keyPressed,KeyReleased, and KeyTyped events, and see if they prevent the key reaching your program.

Your program is probably only looking out for 1 type of key event but you need to find out which one it is and consume those events.

You could try this:

    private void txtDisplayKeyTyped(java.awt.event.KeyEvent evt) {                                          


    boolean valid = false; //some condition here
    if(!valid) evt.consume();
}

See Limit TextField input to numeric value - I think it is exactly what you are looking for.

I think the reason your code does not work is because the if statement is incorrect and isn't actually catch non numeric key codes. Though, I'm not sure because I haven't seen or tested your code myself so you could do some debuging if you really wanted to, but to be honest the solutions posted here will be simplest.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top