Home > Software engineering >  How i can do textField accepts only character "N or E" in Java?
How i can do textField accepts only character "N or E" in Java?

Time:11-05

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?

CodePudding user response:

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);
    }

}

CodePudding user response:

You can try this. This accept only character N

 Pattern pattern = Pattern.compile("N");
        UnaryOperator<TextFormatter.Change> filter = c -> {
            if (pattern.matcher(c.getControlNewText()).matches()) {
                return c ;
            } else {
                return null ;
            }
        };
        TextFormatter<String> formatter = new TextFormatter<>(filter);
        textField.setTextFormatter(formatter);
  • Related