📅  最后修改于: 2023-12-03 15:31:35.742000             🧑  作者: Mango
JavaFX TextField is commonly used to take input from users. Sometimes, we may want to restrict the input to only numbers. In this article, we will discuss how to achieve this in JavaFX.
JavaFX provides us with TextFormatter
class that can be used to modify the text in a TextField
. We can use a regular expression to limit the input to only numbers. Here is an example:
TextField textField = new TextField();
textField.setTextFormatter(new TextFormatter<>(change -> {
String text = change.getText();
if (text.matches("[0-9]*")) {
return change;
}
return null;
}));
In the above code, we created a new TextField
and set a TextFormatter
on it. The TextFormatter
takes a UnaryOperator<TextFormatter.Change>
as a parameter. The UnaryOperator
is a functional interface that takes an argument and returns a result. In our case, the argument is a TextFormatter.Change
and the result is also a TextFormatter.Change
.
Inside the UnaryOperator
, we get the new text that the user entered using change.getText()
. We then check if the text contains only numbers using a regular expression [0-9]*
. If the text contains only numbers, we return the unchanged TextFormatter.Change
. If the text contains anything other than numbers, we return null
which prevents the text from being changed.
We can also restrict the input to only numbers using EventHandler
. Here is an example:
TextField textField = new TextField();
textField.addEventFilter(KeyEvent.KEY_TYPED, event -> {
if (!event.getCharacter().matches("[0-9]")) {
event.consume();
}
});
In the above code, we added an EventHandler
KeyEvent.KEY_TYPED
to the TextField
. The EventHandler
takes a KeyEvent
as a parameter. Inside the EventHandler
, we check if the character typed by the user is a number using a regular expression [0-9]
. If the character is not a number, we consume the event using event.consume()
which prevents the character from being entered in the TextField
.
In this article, we discussed how to restrict the input to only numbers in JavaFX TextField
. We saw how to achieve this using TextFormatter
and EventHandler
. By restricting the input to only numbers, we can improve the user experience and prevent invalid data from being entered in the TextField
.