Search code examples
javaswingjtextfield

JTextField accept only numbers and one dot


I want that my text field accept only numbers (digit) and one dot, because it is a field in which the user can write the price of products. I have this code but it doesn't work well, it only accept numbers and delete.

char c=evt.getKeyChar();
if(!(Character.isDigit(c))||(c==KeyEvent.VK_BACK_SPACE)||(c==KeyEvent.VK_DELETE)){
    getToolkit().beep();
    evt.consume();
}

Can someone help me to fix it?


Solution

  • Don't use a KeyListener. That is old code when using AWT.

    Swing has newer and better API's.

    The easiest way is to use a JFormattedTextField. Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and working examples.

    The other option is so use a DocumentFilter. Read the section from the Swing tutorial on Implementing a DocumentFilter.