java 从 TextField 使用 JavaFX KeyTyped 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15452768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:38:55  来源:igfitidea点击:

Consume JavaFX KeyTyped event from TextField

javajavafx-2textfieldkeyevent

提问by cefeboru

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

我正在尝试验证一个 TextField,我只想在 TextField 上允许数字。我的代码如下所示:

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?

这不会消耗事件 :( 这是一个错误吗?还有其他方法可以做到这一点吗?

回答by Anshul Parashar

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;
}

回答by Uwe

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

从 JavaFX 8u40 开始,限制文本字段输入的最佳方法是在文本字段上设置TextFormatter。有关详细信息,请参阅此答案。无需手动添加事件过滤器或使用事件。

回答by sarcan

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:

我认为使用关键事件是错误的方法。一种可以说更简单、侵入性更小的过滤输入的方法是在 text 属性上安装一个监听器,并在需要时恢复它:

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);
    }
}