我试图阻止用户输入数字,但是只有第二个字符被检查为数字
@FXML
public void enterState()
{
state = stateField.getText();
stateField.textProperty().addListener(new ChangeListener<String>()
{
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue)
{
state = stateField.getText();
String newString = "";
if(!newValue.matches("\\d"))
{
stateField.setText(newValue.replaceAll("-?\\d+(\\.\\d+)?", ""));
state = stateField.getText();
}
if(stateField.getText().length() > 2)
{
newString = stateField.getText().substring(0, stateField.getText().length() - 1);
stateField.setText(newString);
state = stateField.getText();
}
}
});
System.out.println(state);
}
我尝试更改正则表达式匹配,但我无法弄清楚。我的朋友帮我做了这段代码,但他也想不通,因为他最初是为只有数字的条目做的。