问题
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.
回答1:
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 numbers1[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;
}
}
回答2:
I have now revised my code. This code allows you to enter "13" as well as only 13. It also checks if the input is in the range.
Demo App
@Override
public void start(Stage primaryStage) throws Exception {
TextField textField = new TextField();
GridPane gridPane = new GridPane();
Scene scene = new Scene(gridPane);
gridPane.add(textField, 0, 0);
final int MIN = 1;
final int MAX = 19;
UnaryOperator<TextFormatter.Change> filter = change -> {
//if something got added
if (change.isAdded()) {
//if change is " add "" in texfield
if (change.getText().equals("\"")) {
if (!change.getControlText().contains("\"")) {
change.setText("\"\"");
return change;
} else {
//if textfield already contains ""
return null;
}
} else {
//If Input is not a number don't change anything
if (change.getText().matches("[^0-9]")) {
return null;
}
//If change don't contains " check if change is in range
if (!change.getControlText().contains("\"")) {
if (Integer.parseInt(change.getControlNewText()) < MIN || Integer.parseInt(change.getControlNewText()) > MAX) {
return null;
}
} else {
//if change contains "" remove "" and check if is in range
String s = change.getControlNewText();
s = s.replaceAll("[\"]", "");
int value = Integer.parseInt(s);
if (value < MIN || value > MAX) {
return null;
}
}
}
}
return change;
};
textField.setTextFormatter(new TextFormatter<>(filter));
primaryStage.setScene(scene);
primaryStage.show();
}
来源:https://stackoverflow.com/questions/59260621/limit-textfield-to-a-specific-range-of-number-javafx