简体   繁体   English

从TextField消耗JavaFX KeyTyped事件

[英]Consume JavaFX KeyTyped event from TextField

I'm trying to validate a TextField, where I only want to allow numbers on the TextField. 我正在尝试验证TextField,我只想在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? 这不会占用事件:(这是一个错误吗?还有另一种方法可以做到这一点吗?

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

Starting with JavaFX 8u40, the best way to restrict the input of a text field is to set a TextFormatter on the text field. 从JavaFX 8u40开始,限制文本字段输入的最佳方法是在文本字段上设置TextFormatter See this answer for details. 有关详细信息,请参见此答案 No need to add event filters or consume events manually. 无需添加事件过滤器或手动使用事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM