textField.focusedProperty().addListener((arg0, oldValue, newValue) -> {
if (!newValue) {
if(!textField.getText().matches("[1-5]\\.[0-9]|6\\.0")){
textField.setText("");
}
}
});
你也可以将模式更改为[1-5](\.[0-9]){0,1}|6(.0){0,1}
,这样1,2,3,4,5,6
都可以通过验证(不仅限于1.0,2.0,...
)。
更新:下面是一个小的测试应用程序,允许值在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) {
if (!textField1To6.getText().matches("[1-5](\\.[0-9]{1,2}){0,1}|6(\\.0{1,2}){0,1}")) {
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);
}
}
[1-5](\.[0-9]{1,2}){0,1}|6(.0{1,2}){0,1}
。 - griFlo