java - 为 javafx textField 添加最多小数点后 2 位的监听器

标签 java javafx-8 scenebuilder

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

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

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

  @FXML public TextField InvoiceTotal;

 private DoubleProperty invTotal;
 invTotal = new SimpleDoubleProperty(0);

 netAmount.bind(grossAmount.subtract(disc));

 StringConverter<? extends Number> converter= new DoubleStringConverter();

 Bindings.bindBidirectional(InvoiceTotal.textProperty(),invTotal,(StringConverter<Number>)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<Change> filter = c -> {
            if (decimalPattern.matcher(c.getControlNewText()).matches()) {
                return c ;
            } else {
                return null ;
            }
        };

        TextFormatter<Double> 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);
    }
}

关于java - 为 javafx textField 添加最多小数点后 2 位的监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41726257/

相关文章:

java - 具有固定 View y 轴 JavaFX 的滚动 Pane 折线图

java - 当我在initialize()方法中添加TableView功能时按钮停止工作

java - 是否可以 "intercept"复制/剪切/粘贴操作并将其替换为我自己的代码?

java - 如何更改 JFXHamburger 的颜色

JavaFX java.lang.reflect.InitationTargetException(使用场景构建器)

java - 编译 JavaFX 应用程序时出错

java - RabbitMQ 多线程 channel 和队列绑定(bind)

java - Mockito::如何在 Dao 中模拟 SimpleDateFormat.parse()

java - 如何让简单的计算器在android上的EditText中返回最终结果

java - 取消 JAVA JSP 上的预订