Question

I'm trying to only accept numbers (0...9) and the ':' (colon) key in a jTextField, but it doesn't accept the colon key. Why is that?

My code is:

private void horaInicioKeyTyped(java.awt.event.KeyEvent evt) {
    char c=evt.getKeyChar();
    if(!(Character.isDigit(c) || c== KeyEvent.VK_BACK_SPACE || 
         c==KeyEvent.VK_DELETE || (c==KeyEvent.VK_COLON ))){
            evt.consume();
            getToolkit().beep();

    }
}
Was it helpful?

Solution

Don't use VK_COLON, just use ':' like so -

if (Character.isDigit(c) || c==':' || 
      c==KeyEvent.VK_BACK_SPACE || c==KeyEvent.VK_DELETE) {
  evt.consume();
  getToolkit().beep();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top