validate negative numbers

2

I need a JTextField can only accept values of both negative and positive numbers but I can not get the '-'. I've already tried several things.

private void JTPtxKeyTyped(java.awt.event.KeyEvent evt) {
    char a = evt.getKeyChar();

    if ((a<'0' || a>'9' || /*FALTA LA INSTRUCCION PARA ACEPTAR EL MENOS*/)) evt.consume();
}
    
asked by Christian09 21.12.2016 в 03:57
source

2 answers

1

I recommend starting the validation of the character in two parts.

Part 1: if the character is '-' and if the content of the JTextField is empty, then it is valid.

Part 2: if the character is a digit, it is valid.

In code, this would be something like (note, this code can be greatly reduced):

char a = evt.getKeyChar();
boolean valido = false;
if (a == '-') {
    Object component = evt.getComponent();
    if (component instanceof JTextField) {
        JTextField tf = (JTextField)component;
        valido = tf.getText().isEmpty();
    }
} else if (a >= '0' && a <= '9') {
    valido = true;
}
if (!valido) {
    evt.consume();
}
    
answered by 21.12.2016 в 16:41
0

You could work with jspiner and it would no longer be necessary to create anything See here

    
answered by 21.12.2016 в 19:33