0

Well I'm studying Java FX, but this time I'm using FXML in NetBeans, then I want to restric the Keys allowed by a TextField. Like just numbers or just Letters.

I found This , then I created a new class, then put that code (the checked as correct in the link), i extend TextField, but when I run the code, throws a exception, I think is because SceneBuilder doesn't have my Class.

Update i found a similar code for Java FX :

import java.util.function.UnaryOperator;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 *
 * @author Alejandro
 */
public class JavaFXApplication2 extends Application {

@Override
public void start(Stage primaryStage) {

    TextField textField = new TextField();
    TextFormatter<String> textFormatter = getTextFormatter();
    textField.setTextFormatter(textFormatter);

    VBox root = new VBox();

    root.getChildren().add(textField);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("TextFormat");
    primaryStage.setScene(scene);
    primaryStage.show();
}

 private TextFormatter<String> getTextFormatter() {
    UnaryOperator<Change> filter = getFilter();
    TextFormatter<String> textFormatter = new TextFormatter<>(filter);
    return textFormatter;
}

private UnaryOperator<Change> getFilter() {
    return change -> {
        String text = change.getText();

        if (!change.isContentChange()) {
            return change;
        }

        if (text.matches("[a-z]*") || text.isEmpty()) {
            return change;
        }

        return null;
     };
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}

That code above works fine in a Java FX app, but I need one to use in Java FXML, one guy below Post a similar code, it compiles, no trows exception, but doesn't work, or i don't know how to implement it.

Palomino9r
  • 81
  • 8
  • 1
    That link is pretty old. You should use a `TextFormatter` for this kind of functionality. See, e.g. https://stackoverflow.com/questions/40472668/numeric-textfield-for-integers-in-javafx-8-with-textformatter-and-or-unaryoperat – James_D Sep 25 '17 at 17:26

1 Answers1

0

If you want to limit your text to just ALPHA/NUMERIC you can use a textformatter like this:

public class MaxLengthTextFormatter extends TextFormatter<String> {
    private int maxLength;

public MaxLengthTextFormatter(int maxLength) {
    super(new UnaryOperator<TextFormatter.Change>() {
        @Override
        public TextFormatter.Change apply(TextFormatter.Change change) {
            //If the user is deleting the text (i.e. full selection, ignore max to allow the
            //change to happen)
            if(change.isDeleted()) {
                //if the user is pasting in, then the change could be longer
                //ensure it stops at max length of the field
                if(change.getControlNewText().length() > maxLength){
                    change.setText(change.getText().substring(0, maxLength));
                }

            }else if (change.getControlText().length() + change.getText().length() >= maxLength) {
                int maxPos = maxLength - change.getControlText().length();
                change.setText(change.getText().substring(0, maxPos));
            }
            return change;
        }
    });
    this.maxLength = maxLength;
}

public int getMaxLength()
{
    return maxLength;
}

}

public class AlphaNumericTextFormatter extends TextFormatter<String> {

    /** The Constant ALPHA_NUMERIC_ONLY. */
    //private static final String ALPHA_NUMERIC_ONLY = "^[a-zA-Z0-9]*$";
    /** MAKE NUMERIC ONLY **/
    private static final String DIGITS_ONLY = "^[0-9]*$";

    /**
     * Instantiates a new alpha numeric text formatter.
     */
    public AlphaNumericTextFormatter() {
        super(applyFilter(null));
    }

    /**
     * Instantiates a new alpha numeric text formatter.
     *
     * @param maxLength
     *            the max length
     */
    public AlphaNumericTextFormatter(int maxLength) {
        super(applyFilter(new MaxLengthTextFormatter(maxLength).getFilter()));
    }

    /**
     * Apply filter.
     *
     * @param filter
     *            the filter
     * @return the unary operator
     */
    private static UnaryOperator<Change> applyFilter(UnaryOperator<Change> filter) {
        return change -> {
            if (change.getControlNewText() != null && change.getControlNewText().matches(DIGITS_ONLY)) {
                if (filter != null) {
                    filter.apply(change);
                }
                return change;
            }
            return null;
        };
    }

}

That creates a formatter than only allows numbers and letters - you can adjust the pattern to your needs.

You attach it to your textfield like this....

@FXML
private TextField myTextField;


@FXML
private void initialize() {
    //Create a alpha field which max length of 4
    myTextField.setTextFormatter(new AlphaNumericTextFormatter(4));
}
purring pigeon
  • 4,141
  • 5
  • 35
  • 68
  • Thanks for answering, the code works but I didn't explain enough, I want to catch the KeyEvent and don't allow to be displayed in the TextField. – Palomino9r Sep 25 '17 at 23:23
  • Not sure I understand what you are asking. You want to restrict all key input? If so, set the textfield to not editable. Is that what you are asking? – purring pigeon Sep 26 '17 at 13:14
  • Not all key input, just restrict​ some keys, in the TextField to make it just Numeric or just A-Z. Is for a validation process, like when you type your name in a sign in, the system just let you type letters, not Numeric neither special characters. – Palomino9r Sep 26 '17 at 14:14
  • You just need to change the regex to allow the values you want. Change this variable - private static final String ALPHA_NUMERIC_ONLY = "^[a-zA-Z0-9]*$"; For example you could use this "^[0-9]*$" - I will edit to show numbers only. – purring pigeon Sep 26 '17 at 14:22
  • First thanks for trying to help me, I update the post, I found code similar to yours, is for Java FX, maybe I don't know how to use your code, pls check it. – Palomino9r Sep 26 '17 at 15:56