【问题标题】:How i can do textField accepts only character "N or E" in Java?我怎么能做 textField 在 Java 中只接受字符“N 或 E”?
【发布时间】:2021-12-18 16:14:02
【问题描述】:

我如何做 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还是单字母E?或它们的任何组合,例如NE, NNNNN, EEEEEE, ENEN?
  • 使用TextFormatter。不要使用侦听器来修改更改。看看stackoverflow.com/questions/34407694/… 是否回答了你的问题。
  • @guninvalid 不,我的意思是只得到单个字母 N 或 E。
  • 还要注意,如果用户需要在两个选项之间进行选择,TextField 可能不是最好的用户体验。请考虑使用单选按钮、复选框或组合框。
  • 你的任务是什么?为什么它需要那样工作?

标签: java validation javafx textfield


【解决方案1】:

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

}

【讨论】:

  • 谢谢你,这很好用。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多