【问题标题】:Handling Infinity in JavaFX numerical TextField处理 JavaFX 数值 TextField 中的无穷大
【发布时间】:2021-08-30 18:44:44
【问题描述】:

我有一个 JavaFX TextField 专门接受数字,包括科学记数法。它几乎可以完成我想要的一切。但是,因为它接受科学记数法,所以用户很容易输入超出double 可以表示的范围的数字。当他们这样做时,TextField 会显示“Infinity”(或“-Infinity”)。发生这种情况时,无法再编辑该字段来纠正问题。内容也无法选择和删除。点击“Escape”键不会返回之前的内容。

这是一个 SSCCE,它与几年前 James_D 的 answer 和 question 密切相关。

import java.text.DecimalFormatSymbols;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class NumericTextFieldDemo extends Application {

    char sep = new DecimalFormatSymbols().getDecimalSeparator();
    String negStarter = new StringBuilder("-").append(sep).toString();
    String posStarter = new StringBuilder("+").append(sep).toString();
    String patternStr = new StringBuilder()
            .append("[+|-]?(([1-9][0-9]*)|0)?(\\")
            .append(sep)
            .append("[0-9]*)?(([e|E][+|-]?[0-9]*)?)")
            .toString();
    Pattern validEditingState = Pattern.compile(patternStr);

    class NumericTextField extends TextField {

        UnaryOperator<TextFormatter.Change> filter = c -> {
            String text = c.getControlNewText();
            if (validEditingState.matcher(text).matches()) {
                return c;
            } else {
                return null;
            }
        };

        StringConverter<Double> converter = new StringConverter<Double>() {

            @Override
            public Double fromString(String s) {
                if (s.isEmpty() || "-".equals(s) || "+".equals(s)
                        || negStarter.equals(s) || posStarter.equals(s)) {
                    return 0.0;
                } else {
                    return Double.valueOf(s);
                }
            }

            @Override
            public String toString(Double d) {
                return d.toString();
            }
        };

        NumericTextField(double initValue) {
            TextFormatter<Double> textFormatter = new TextFormatter<>(converter, initValue, filter);
            textFormatter.valueProperty().addListener((ObservableValue<? extends Double> obs, Double oldValue, Double newValue) -> {
                System.out.println("User entered value: " + newValue);
            });
            setTextFormatter(textFormatter);
        }

        NumericTextField() {
            this(0.0);
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        NumericTextField ntf = new NumericTextField();
        // Setting the font seems to be required on macOS.
        ntf.setFont(new Font("Arial", 14));

        VBox root = new VBox(5, ntf);
        root.setAlignment(Pos.CENTER);
        primaryStage.setScene(new Scene(root, 250, 150));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

有什么方法可以捕捉无穷大并使TextField 处于可用状态?是否可以对班级进行一些更改以防止首先输入此类数字?

【问题讨论】:

  • 在返回之前测试Double.valueOf(s)的结果?还是使用BigDecimal?
  • macOS 不需要设置字体。
  • 对其他问题/答案的评论相同:不要进行任何手动模式匹配(它会因不同的语言环境而中断),而是使用 NumberFormat。另外:永远不要仅仅为了配置而扩展一个类——而是使用工厂模式。
  • @swpalmer, bugs.openjdk.java.net/browse/JDK-8234916 讨论了乱码文本字体和错误。在 JavaFX 14 中已修复。我仅限于 11。

标签: regex javafx textfield


【解决方案1】:

只需使用内置的字符串转换器进行双打:

    TextFormatter<Double> tf = new TextFormatter<>(new DoubleStringConverter());
    TextField ntf = new TextField();
    ntf.setTextFormatter(tf);

【讨论】:

  • 嗯,这当然更容易!谢谢。
猜你喜欢
  • 2020-09-02
  • 1970-01-01
  • 2022-08-12
  • 2022-01-26
  • 2014-04-24
  • 2018-09-23
  • 2014-05-08
  • 2017-11-03
相关资源
最近更新 更多