How i can do textField accepts only character "N or E" in Java?

How i can do textField accepts only letter "N or E" in Java? doesn’t accept number and another characters.

        textField.textProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.length() > 1) textField.setText(oldValue);
            if (newValue.matches("[^\\d]")) return;
            textField.setText(newValue.replaceAll("\\d*", ""));

i tryed this, this worked for maxValue. But i am need textField accept only "N" and "E" characters.
So how i can do this?

>Solution :

Use a TextFormatter. You can modify or veto the proposed change to the text. This version:

  • Only accepts changes where the text typed (or pasted) is "N" or "E" (either upper or lower case)
  • Makes the text upper case
  • Changes the proposed change so that it replaces existing text, instead of adding to it
  • Allows for deleting the current text

Your exact requirements may differ slightly. See the Javadocs for TextFormatter.Change for more details.

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.layout.BorderPane;
import javafx.stage.Stage;

public class NorETextField extends Application {

    public void start(Stage primaryStage) throws Exception {
        TextField textField = new TextField();
        UnaryOperator<TextFormatter.Change> filter = c -> {
            if (c.getText().matches("[NnEe]")) {
                c.setRange(0, textField.getText().length());
                return c ;
            } else if (c.getText().isEmpty()) {
                return c ;
            return null ;
        textField.setTextFormatter(new TextFormatter<String>(filter));
        BorderPane root = new BorderPane(textField);
        Scene scene = new Scene(root, 400, 250);

    public static void main(String[] args) {


Leave a Reply