我正在尝试创建一个只接受双打的字段。我希望在没有用户点击输入的情况下提交值。因此,我正在设置监听器,以便每次都进行更改并设置值。
以下是我的一些代码:
// Change the behaviour of the converter to avoid empty strings and values outside the defined bounds
valueFactory.setConverter(new StringConverter<Double>() {
private final DecimalFormat format = new DecimalFormat("#.##");
@Override
public String toString(Double value) {
if (value == null) {
return format.format(0);
}
return value.toString();
}
@Override
public Double fromString(String string) {
try {
if (string == null || string.trim().length() < 0 || string.trim().length() > MAX_LENGTH) {
return null;
} else {
Double newVal = format.parse(string).doubleValue();
return (newVal >= min && max >= newVal) ? newVal : null;
}
} catch (Exception ex) {
return 0.00;
}
}
});
// Define a formatter on the text entered into the field
TextFormatter<Object> textFormatter = new TextFormatter<>(c -> {
if (c.getText().matches("[^0-9.]+") && !c.getText().trim().isEmpty()) {
return null;
}
if(c.getControlNewText().length() <= MAX_LENGTH) {
try {
Double newVal = Double.valueOf(c.getControlNewText());
return (newVal >= min && max >= newVal) ? c : null;
} catch (Exception ex) {
if(c.getControlNewText().isEmpty()) {
c.setText("0.00");
} else if(c.getControlNewText().length() == 1) {
c.setText("0.00");
} else {
c.setText("");
}
return c;
}
} else {
c.setText("");
return c;
}
});
getEditor().setTextFormatter(textFormatter);
getEditor().textProperty().addListener(new ChangeListener<String>() {
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if(!newValue.trim().isEmpty()) {
try {
setValue(Double.parseDouble(newValue), amountToStepBy);
} catch(Exception e) {
setValue(min, amountToStepBy);
getEditor().setText(min.toString());
}
}
}
});
我希望用户只能以#。##格式添加双号。问题是,当我输入一个像0.00000001这样的数字时,这会失败,我得到一个例外:
java.lang.IllegalArgumentException: The start must be <= the end
at javafx.scene.control.TextInputControl.getText(TextInputControl.java:446)
at javafx.scene.control.TextInputControl.updateContent(TextInputControl.java:564)
at javafx.scene.control.TextInputControl.replaceText(TextInputControl.java:548)
at com.sun.javafx.scene.control.skin.TextFieldSkin.replaceText(TextFieldSkin.java:576)
此外,文本字段的编辑值为1.0E-8。