How can you enter only numbers in the text field, or vice versa, enter only alphabetic characters. I searched on the Internet, I did not find any sane decisions.
2 answers
There is a very simple solution - to hang a lineer to change the text and look at the regular expression that it fits.
String numberMatcher = "^-?\\d+$"; //t1 - новый текст, s - старый текст. textBox.textProperty().addListener((observableValue, s, t1) - > { if (!t1.isEmpty()) { if (!t1.matches(numberMatcher)) { textBox.setText(s); } else { try { // тут можете парсить строку как захотите int value = Integer.parseInt(t1); textBox.setText(value); } catch (NumberFormatException e) { this.setText(s); } } } });
- Please describe what "^ -? \\ d + $" means - arachnoden
- oneRead about regular expressions. And this line means that you can enter both positive numbers and negative ones. - Andrew Bystrov
|
I created a class that extends TextField and redefined replaceText
@Override public void replaceText(int start, int end, String text) { if (!"1234567890.\b".contains(text)){text = "";} }
|