JavaFX输入验证文本字段

BRs*_*ver 4 java javafx

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

我希望他们成为学校标记,所以他们应该只允许在1.0和6.0之间.不应该允许用户写"2.34.4"之类的东西,但是"5.5"或"2.9"之类的东西也可以.

验证已解析的字段:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

gri*_*Flo 8

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

    });
Run Code Online (Sandbox Code Playgroud)

你也可以改变模式[1-5](\.[0-9]){0,1}|6(.0){0,1}然后1,2,3,4,5,6也可以(不仅如此1.0,2.0,...)

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

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

}
Run Code Online (Sandbox Code Playgroud)


小智 5

我不建议您为此使用KeyEvent。

您应该使用更经典的方式,例如在用户填写文本字段或单击保存按钮时验证用户输入。

/**
 * Called this when the user clicks on the save button or finish to fill the text field.
 */
private void handleSave() {
        // If the inputs are valid we save the data
        if(isInputValid()){
            note=(DOUBLE.parseDouble(textField.getText()));
        }else // do something such as notify the user and empty the field
}

/**
 * Validates the user input in the text fields.
 * 
 * @return true if the input is valid
 */
private boolean isInputValid() {
    Boolean b= false;
    if (!(textField.getText() == null || textFiled.getText().length() == 0)) {
        try {
            // Do all the validation you need here such as
            Double d = Double.parseInt(textFiled.getText());
            if ( 1.0<d<6.0){
                b=true;
            }
        } catch (NumberFormatException e) { 
        }
    return b;
}
Run Code Online (Sandbox Code Playgroud)