Consume JavaFX KeyTyped event from TextField

14,519

Solution 1

try this its worked..

txtMobile.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent event) {
        String character=event.getCharacter();


        if(!valid.checkNumeric(character))
            event.consume();                    
    }});

and the function for numeric...

public boolean checkNumeric(String value)    {
    String number=value.replaceAll("\\s+","");
    for(int j = 0 ; j<number.length();j++){ 
            if(!(((int)number.charAt(j)>=47 && (int)number.charAt(j)<=57)))
            {
                return false;
            }
    }     
    return true;
}

Solution 2

I think consuming the key events is the wrong approach to this. An arguably simpler and less invasive way to filter the input is to install a listener on the text property and revert it if needed:

public class Test extends Application {
    @Override
    public void start(final Stage stage) throws Exception {
        final Pattern wholeNumberPattern = Pattern.compile("\\d*");
        final TextField tf = new TextField();
        tf.textProperty().addListener(new ChangeListener<String>() {
            public void changed(final ObservableValue<? extends String> observableValue, final String oldValue,
                                final String newValue) {
                if (!wholeNumberPattern.matcher(newValue).matches())
                    tf.setText(oldValue);
            }
        });
        stage.setScene(new Scene(tf));
        stage.show();
    }

    public static void main(String[] args) {
        System.out.println(com.sun.javafx.runtime.VersionInfo.getRuntimeVersion());
        Application.launch(args);
    }
}

Solution 3

Starting with JavaFX 8u40, the best way to restrict the input of a text field is to set a TextFormatter on the text field. See this answer for details. No need to add event filters or consume events manually.

Share:
14,519
cefeboru
Author by

cefeboru

Software Developer @ PartnerHero

Updated on June 04, 2022

Comments

  • cefeboru
    cefeboru almost 2 years

    I'm trying to validate a TextField, where I only want to allow numbers on the TextField. My code looks like this:

    public void handle(KeyEvent evt) {
        String character = evt.getCharacter();
        if(!character.equals("1")) {
            JOptionPane.showMessageDialog(null,evt.getCharacter());
            evt.consume();                
        }                                         
    }
    

    This doesn't consume the event :( Is this a bug? Is there another way to do this?