JavaFX输入验证文本字段 [英] JavaFX Input Validation Textfield

查看:657
本文介绍了JavaFX输入验证文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaFX和Scene Builder,我有一个带有文本字段的表单。其中三个文本字段从字符串解析为双精度。

I'm using JavaFX and Scene Builder and I have a form with textfields. Three of these textfields are parsed from strings to doubles.

我希望它们成为学校标记,因此它们应该只允许在1.0到6.0之间。不应该允许用户写2.34.4之类的东西,但是5.5或2.9之类的东西也可以。

I want them to be school marks so they should only be allowed to be between 1.0 and 6.0. The user should not be allowed to write something like "2.34.4" but something like "5.5" or "2.9" would be ok.

验证已解析的字段:

public void validate(KeyEvent event) {
    String content = event.getCharacter();
    if ("123456.".contains(content)) {
            // No numbers smaller than 1.0 or bigger than 6.0 - How?
    } else {
        event.consume();
    }
}

如何测试用户输入的值是否正确?

How can I test if the user inputs a correct value?

我已经在Stackoverflow和Google上搜索过但我找不到令人满意的解决方案。

I already searched on Stackoverflow and on Google but I didn't find a satisfying solution.

推荐答案

textField.focusedProperty().addListener((arg0, oldValue, newValue) -> {
        if (!newValue) { //when focus lost
            if(!textField.getText().matches("[1-5]\\.[0-9]|6\\.0")){
                //when it not matches the pattern (1.0 - 6.0)
                //set the textField empty
                textField.setText("");
            }
        }

    });

您还可以将模式更改为 [1-5](\ 。[0-9]){0,1} | 6(.0){0,1} 然后 1,2,3,4,5,6 也可以(不仅 1.0,2.0,...

you could also change the pattern to [1-5](\.[0-9]){0,1}|6(.0){0,1} then 1,2,3,4,5,6would also be ok (not only 1.0,2.0,...)

更新
这是一个允许值为1(.00)到6(.00)的小型测试应用程序:

update Here is a small test application with the values 1(.00) to 6(.00) allowed:

public class JavaFxSample extends Application {

@Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Enter number and hit the button");
    GridPane grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    Label label1To6 = new Label("1.0-6.0:");
    grid.add(label1To6, 0, 1);
    TextField textField1To6 = new TextField();

    textField1To6.focusedProperty().addListener((arg0, oldValue, newValue) -> {
        if (!newValue) { // when focus lost
                if (!textField1To6.getText().matches("[1-5](\\.[0-9]{1,2}){0,1}|6(\\.0{1,2}){0,1}")) {
                    // when it not matches the pattern (1.0 - 6.0)
                    // set the textField empty
                    textField1To6.setText("");
                }
            }
        });
    grid.add(textField1To6, 1, 1);
    grid.add(new Button("Hit me!"), 2, 1);
    Scene scene = new Scene(grid, 300, 275);
    primaryStage.setScene(scene);
    primaryStage.show();
}

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

}

这篇关于JavaFX输入验证文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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