Search code examples
javavalidationjtextfield

Valide comma or dot Jtextfield


as allowing the dot or comma, I use validation numbers, but I need to allow comma and period (dot).

public static void lNum(JTextField txt){
    txt.addKeyListener(new KeyAdapter(){
        @Override
        public void keyTyped(KeyEvent e){
            char c = e.getKeyChar();
            if(!Character.isDigit(c))
                e.consume();
        }
        @Override
        public void keyPressed(KeyEvent arg0) {
            }
        @Override
        public void keyReleased(KeyEvent arg0) {
           }
    });
}

Solution

  • Just add this in your condition

    String.valueOf(e.getKeyChar()).matches(",") 
    

    and

    String.valueOf(e.getKeyChar()).matches("\\.")