user3196284
user3196284

Reputation:

JavaFX custom TextField restriction

I'm making an application for my math teacher to convert a plane from its vector equation form to its scalar equation form.

For my input TextField I have this code.

TextField input = new TextField();
input.setPromptText(" (x,y,z) + q(a,b,c) + p(a,b,c) ");

I want to restrict the input to the given format (Restricting input format in general).

The only way I could think of doing this, would be to have a thread or action listener constantly calling

input.getText();

Then comparing every index of the string to see if it is the correct type of input (Is a number, or is a bracket... etc).

This seems like a very "noobish" way of doing it... Does anyone know of a better way of doing this? Perhaps java has some built in methods for it?

Upvotes: 2

Views: 1106

Answers (2)

Madushan Perera
Madushan Perera

Reputation: 2598

You can use controls FX validation support to make this work :

In your controller u can set validator to your text field:

validationSupport = new ValidationSupport();
        validationSupport.registerValidator(textField, true, ValidationForm.formatValidate);

Then you can design your validator as you need inside a separate class:

public class ValidationForm {

    /**
     * Field allows only if correctly formatted
     */
    public static Validator<String> formatValidate = (Control control, String value) -> {
        boolean condition = value != null
                ? !value.matches("^\\({1}+[0-9]+\\,[0-9]+\\,[0-9]+\\){1}+\\+{1}"
                        + "+[a-z]{1}+\\({1}+[0-9]+\\,[0-9]+\\,[0-9]+\\){1}+\\+{1}"
                        + "+[a-z]{1}+\\({1}+[0-9]+\\,[0-9]+\\,[0-9]+\\){1}$") : value == null;

        return ValidationResult.fromMessageIf(control, "Not a valid input \n"
                + "Should be formatted \" (x,y,z) + q(a,b,c) + p(a,b,c) \"",
               Severity.ERROR, condition);
    };
   ...

Upvotes: 2

jewelsea
jewelsea

Reputation: 159290

Look into the 3rd party Controls FX library which features validation/decoration of input controls and for which you can createRegExValidator. Use regex101 to fashion your regex. Once validation passes, you can use pattern matching on the regex to retrieve the input values from the input string.

As this is mainly a learning exercise for you, I won't supply the code for this at the moment.

Upvotes: 1

Related Questions