我该怎么做 textField 只接受 Java 中的字符 "N or E"?

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

我该怎么做 textField 只接受 Java 中的字母“N 或 E”?不接受数字和其他字符。

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

我试过了,这对 maxValue 有效。但我需要 textField 只接受“N”和“E”字符。 那我该怎么做呢?

你可以试试这个。这只接受字符 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);

使用 TextFormatter。您可以修改或否决对文本的提议更改。这个版本:

  • 仅接受键入(或粘贴)的文本为“N”或“E”(大写或小写)的更改
  • 使文本大写
  • 更改提议的更改以替换现有文本,而不是添加文本
  • 允许删除当前文本

您的具体要求可能略有不同。有关详细信息,请参阅 Javadocs for TextFormatter.Change

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

}