是否将TextField限制为JavaFX数字的特定范围? [英] Limit TextField to a specific range of number JavaFX?

查看:348
本文介绍了是否将TextField限制为JavaFX数字的特定范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不仅需要限制TextField javaFX的输入,而且还必须限制1-19之间的数字.例如,应该允许我输入:"3","19" ...,但不能输入:"33,44 ..例如:

TextField验证演示

 公共类TextFieldValidationDemo扩展了Application {私有静态最终字符串REGEX_VALID_INTEGER =([[1-9] | 1 [0-9]])";@Overridepublic void start(Stage primaryStage)引发异常{BorderPane根=新的BorderPane();root.setCenter(getRootPane());primaryStage.setScene(new Scene(root,200,200));primaryStage.show();}私人BorderPane getRootPane(){BorderPane根=新的BorderPane();root.setCenter(getTextField());返回根}私人TextField getTextField(){TextField字段=新的TextField();field.setTextFormatter(new TextFormatter<>(this :: filter));返回字段;}私人TextFormatter.Change过滤器(TextFormatter.Change更改){如果(!change.getControlNewText().matches(REGEX_VALID_INTEGER)){change.setText(");}退货变更;}} 

Hi I need to limit the input of TextField javaFX not only for integer but also for numbers between 1 - 19 only.For example I should be allowed to type : "3" ,"19" ... but not: "33" , 44 .. for example : What is the recommended way to make a numeric TextField in JavaFX? but this limits the text field just for integers.

解决方案

You can use regex to allow your specific numbers' range(1-19) and add that validation on TextField's TextFormatter's filter.

Regex => ([1-9]|1[0-9])

  • [1-9] Either TextField allows you to enter 1 to 9 numbers
  • 1[0-9] Or TextField allows you to enter 10 to 19 numbers

Regex Circut

TextField Validation Demo

public class TextFieldValidationDemo extends Application {

    private static final String REGEX_VALID_INTEGER = "([1-9]|1[0-9])";

    @Override
    public void start(Stage primaryStage) throws Exception {
        BorderPane root = new BorderPane();
        root.setCenter(getRootPane());
        primaryStage.setScene(new Scene(root, 200, 200));
        primaryStage.show();
    }

    private BorderPane getRootPane() {
        BorderPane root = new BorderPane();
        root.setCenter(getTextField());
        return root;
    }

    private TextField getTextField() {
        TextField field = new TextField();
        field.setTextFormatter(new TextFormatter<>(this::filter));
        return field;
    }

    private TextFormatter.Change filter(TextFormatter.Change change) {
        if (!change.getControlNewText().matches(REGEX_VALID_INTEGER)) {
            change.setText("");
        }
        return change;
    }
}

这篇关于是否将TextField限制为JavaFX数字的特定范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆