为javafx textField添加最多2位小数的侦听器

我想将javaFX文本字段设置为两位小数。 我找到了答案,但它是数值。 例如

// force the field to be numeric only textField.textProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observable, String oldValue, String newValue) { if (!newValue.matches("\\d*")) { textField.setText(newValue.replaceAll("[^\\d]", "")); } } }); 

在上面的代码中,什么是最多两位小数的限制值的替换。 或者是否有任何其他解决方案来限制textField。 我有绑定TextField这是我的部分代码…

  @FXML public TextField InvoiceTotal; private DoubleProperty invTotal; invTotal = new SimpleDoubleProperty(0); netAmount.bind(grossAmount.subtract(disc)); StringConverter converter= new DoubleStringConverter(); Bindings.bindBidirectional(InvoiceTotal.textProperty(),invTotal,(StringConverter)converter); 

现在我想在InvoiceTotal文本字段上设置两个小数限制

在文本字段上使用文本格式化程序。 该模式必须匹配任何可能的十进制值,最多两位小数。 (类似于可选的否定符号,后跟任意数量的数字,然后可选地后跟小数点和0-2位数。)如果结果文本与该模式匹配,只需让文本格式化程序接受更改,否则拒绝它们。

 import java.util.function.UnaryOperator; import java.util.regex.Pattern; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.control.TextFormatter.Change; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class DecimalTextField extends Application { @Override public void start(Stage primaryStage) { Pattern decimalPattern = Pattern.compile("-?\\d*(\\.\\d{0,2})?"); UnaryOperator filter = c -> { if (decimalPattern.matcher(c.getControlNewText()).matches()) { return c ; } else { return null ; } }; TextFormatter formatter = new TextFormatter<>(filter); TextField textField = new TextField(); textField.setTextFormatter(formatter); StackPane root = new StackPane(textField); root.setPadding(new Insets(24)); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } } 

我无法抗拒。 这是两行中的答案(完成所有工作的那些)

 private static TextFormatter new3DecimalFormatter(){ Pattern decimalPattern = Pattern.compile("-?\\d*(\\.\\d{0,3})?"); return new TextFormatter<>(c -> (decimalPattern.matcher(c.getControlNewText()).matches()) ? c : null ); }