event.consume()方法在javafx中不起作用

时间:2018-09-13 05:41:01

标签: java javafx

以下是我的代码。但是,当我插入数字时,文本字段仍会显示它。为什么呢?

    supMobileText1.setOnKeyPressed(new EventHandler<KeyEvent>(){

        @Override
        public void handle(KeyEvent event) {
            if(event.getCode().isDigitKey()) {
                event.consume();
                System.out.println("Number Type");
            }

        }

    });

1 个答案:

答案 0 :(得分:0)

这将只允许输入字母

public class Main extends Application {

    public static void main(String[] args) { launch(args); }

    @Override
    public void start(Stage primaryStage) {
        TextField textField = new TextField();

        Pattern pattern = Pattern.compile("[a-zA-Z]*");
        UnaryOperator<TextFormatter.Change> filter = c -> {
            if (pattern.matcher(c.getControlNewText()).matches()) {
                return c ;
            } else {
                return null ;
            }
        };
        TextFormatter<String> formatter = new TextFormatter<>(filter);
        textField.setTextFormatter(formatter);

        Scene scene = new Scene(textField);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}