首页 > 解决方案 > 如何在javafx中将文本字段输入更改为仅数字?

问题描述

我的 java fx 程序中有一个信用卡页面。我正在努力使输入只允许数字。目前,如果字段为空,它只会给出错误。但是如果包含文本不会发生错误?

我尝试将其从字符串更改为整数,但这不起作用。

public void thankyoupage(ActionEvent actionEvent) throws IOException {
        String cardno = cardtf.getText();
        String expdate1 = expirytf1.getText();
        String expdate2 = expirytf2.getText();
        String cvvnum = cvvtf.getText();

        if (cardno.equals("") || expdate1.equals("") ||
                expdate2.equals("") || cvvnum.equals("")) {
            Alert alert = new Alert(Alert.AlertType.WARNING, "Enter Full Details", ButtonType.OK);

            alert.showAndWait();
        }    else{
            Window mainWindow = confirmbut.getScene().getWindow();
            Parent newRoot = FXMLLoader.load(getClass().getResource("Thankyou.fxml"));
            mainWindow.getScene().setRoot(newRoot);
        }
    }

任何链接或更改都会很好。

标签: javafx

解决方案


您应该将 TextFormatter 附加到您的 TextField。我附上了使用小数的示例——因为你使用的是钱,这可能是最有意义的。

在您的文本字段中,您只需添加 TextFormatter - 这将防止输入您允许之外的任何内容。

//For Example
moneyTextField.setTextFormatter(new DecimalTextFormatter(0, 2));

--下面是控制代码。

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.function.UnaryOperator;

import javafx.scene.control.TextFormatter;
import javafx.util.StringConverter;

public class DecimalTextFormatter extends TextFormatter<Number> {
    private static DecimalFormat format = new DecimalFormat("#.0;-#.0");

    public DecimalTextFormatter(int minDecimals, int maxDecimals) {
        super(getStringConverter(minDecimals, maxDecimals), 0, getUnaryOperator(maxDecimals, true,-1));
    }

    public DecimalTextFormatter(int minDecimals, int maxDecimals, boolean allowsNegative) {
        super(getStringConverter(minDecimals, maxDecimals), 0, getUnaryOperator(maxDecimals, allowsNegative,-1));
    }

    public DecimalTextFormatter(int minDecimals, int maxDecimals, boolean allowsNegative , int maxNoOfDigitsBeforeDecimal) {
        super(getStringConverter(minDecimals, maxDecimals), 0, getUnaryOperator(maxDecimals, allowsNegative, maxNoOfDigitsBeforeDecimal));
    }

    private static StringConverter<Number> getStringConverter(int minDecimals, int maxDecimals) {
        return new StringConverter<Number>() {
            @Override
            public String toString(Number object) {
                if (object == null) {
                    return "";
                }
                String format = "0.";
                for (int i = 0; i < maxDecimals; i++) {
                    if (i < minDecimals) {
                        format = format + "0";
                    } else {
                        format = format + "#";
                    }
                }
                format = format + ";-" + format;
                DecimalFormat df = new DecimalFormat(format);
                String formatted = df.format(object);
                return formatted;
            }

            @Override
            public Number fromString(String string) {
                try {
                    if (string == null) {
                        return null;
                    }
                    return format.parse(string);
                } catch (ParseException e) {
                    return null;
                }
            }
        };
    }

    private static UnaryOperator<javafx.scene.control.TextFormatter.Change> getUnaryOperator(int maxDecimals,
            boolean allowsNegative, int noOfDigitsBeforeDecimal) {
        return new UnaryOperator<TextFormatter.Change>() {
            @Override
            public TextFormatter.Change apply(TextFormatter.Change change) {
                if (!allowsNegative && change.getControlNewText().startsWith("-")) {
                    return null;
                }

                if (change.getControlNewText().isEmpty()) {
                    return change;
                }

                ParsePosition parsePosition = new ParsePosition(0);
                Object object = format.parse(change.getControlNewText(), parsePosition);

                if (change.getCaretPosition() == 1) {
                    if (change.getControlNewText().equals(".")) {
                        return change;
                    }
                }

                if (object == null || parsePosition.getIndex() < change.getControlNewText().length()) {
                    return null;
                } else {

                    if(noOfDigitsBeforeDecimal != -1)
                    {
                        int signum = new BigDecimal(change.getControlNewText()).signum();
                        int precision = new BigDecimal(change.getControlNewText()).precision();
                        int scale = new BigDecimal(change.getControlNewText()).scale();

                        int val = signum == 0 ? 1 : precision - scale;
                        if (val > noOfDigitsBeforeDecimal) {
                            return null;
                        }
                    }

                    int decPos = change.getControlNewText().indexOf(".");
                    if (decPos > 0) {
                        int numberOfDecimals = change.getControlNewText().substring(decPos + 1).length();
                        if (numberOfDecimals > maxDecimals) {
                            return null;
                        }
                    }
                    return change;
                }
            }
        };
    }
}

推荐阅读