Control keyboard input into javafx TextField

后端 未结 6 1762
清酒与你
清酒与你 2020-12-31 17:44

I want to control the input into a Javafx TextField so that I can allow only Numeric input, and so that if the max characters are exceeded, then no change will be made to th

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 18:09

    Here is my aproach, two event filters, could be one, in my case i used them in diferent situations, thats why there are two.

    Here is the maxValueFilter (in spanglish xD), this one is a class:

    public class FilterMaxValue implements EventHandler {
    
            private int maxVal;
    
            public FilterMaxValue (int i) {
                this.maxVal= i;
            }
    
            public void handle(KeyEvent arg0) {
    
                TextField tx = (TextField) arg0.getSource();
                String chara = arg0.getCharacter();
                if (tx.getText().equals(""))
                    return;
    
                Double valor;
                if (chara.equals(".")) {
                    valor = Double.parseDouble(tx.getText() + chara + "0");
                } else {
                    try {
                        valor = Double.parseDouble(tx.getText() + chara);
                    } catch (NumberFormatException e) {
                        //The other filter will prevent this from hapening
                        return;
                    }
                }
                if (valor > maxVal) {
                    arg0.consume();
                }
    
            }
        }
    

    And the other event filter (filters the chars), this one is a method:

    public static EventHandler numFilter() {
    
            EventHandler aux = new EventHandler() {
                public void handle(KeyEvent keyEvent) {
                    if (!"0123456789".contains(keyEvent.getCharacter())) {
                        keyEvent.consume();
    
                    }
                }
            };
            return aux;
        }
    

    the use in your case would be:

    field.addEventFilter(KeyEvent.KEY_TYPED,
                    numFilter());
    field.addEventFilter(KeyEvent.KEY_TYPED, new FiltroValorMaximo(
                    99));
    

提交回复
热议问题