Mohamad S.
Mohamad S.

Reputation: 209

TextField that accepts only positive numbers - JavaFX

I'm trying to create a TextField in JavaFX (using Scene Builder) that accepts only positive numbers.

I'm trying actually to make a TextField for a 'Credit Card Number' which accepts 13 - 16 numeric values, not including the minus sign at the beginning, and which can accept 0 at the beginning of the text.

Also, since it's a 'Credit Card Number' TextField, I'm looking for a way where I can insert automatic space after each 4 letters/numbers inserted to it.

Note: I know how to create a TextField that accepts only numbers but it also accepts minus sign at the beginning and doesn't accept the 0 as the first input.

Upvotes: 0

Views: 1226

Answers (1)

BlacKnight BK
BlacKnight BK

Reputation: 119

Here is what I have been using so my TextField only accepts digits and it works like a charm as below,

public static void digitsTxtFld(TextField field) {
    field.setTextFormatter(new TextFormatter<Integer>(change -> {
        String newText = change.getControlNewText();
        if (newText.matches("\\d*")) {
            return change;
        }
        return null;
    }));
}

And to set a character limit I use this,

    public static void setTextLimit(TextArea textArea, int length) {
        textArea.setTextFormatter(new TextFormatter<>(change -> {
            String string = change.getControlNewText();
            if (string.length() > length) {
                textArea.positionCaret(string.length());
                return change;
            } else {
                return null;
            }
        }));
    }

Edit: Apparently one cannot have both text formatters as the second one you call will replace the first and your field will only run with one at a time. So I made a joint formatter as follows:

    public static void setTextLimitToDigitFld(TextField field, int length) {
        field.setTextFormatter(new TextFormatter<Integer>(change -> {
            String newText = change.getControlNewText();
            if (newText.matches("\\d*") && newText.length() > length) {
                return change;
            }
            return null;
        }));
    }

Upvotes: -2

Related Questions