Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 {

    @Override
    public void start(Stage primaryStage) throws Exception {
        TextField textField = new TextField();
        UnaryOperator<TextFormatter.Change> filter = c -> {
            if (c.getText().matches("[NnEe]")) {
                c.setText(c.getText().toUpperCase());
                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);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading