Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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.

Validation for the parsed fields:

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
538 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

    });

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,...)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...