您可以使用
TextFormatter和
String's
matches。
如果中的文本
TextField不符合这三个条件之一
Regex,则显示旧文本。
case 1: newVal.matches("[A-z]") -> Single alpha charactercase 2: newVal.matches("[A-z]\d+") -> Alpha character followed by digitscase 3: newVal.matches("[A-z]\d+[A-z]") -> Alpa character followed by digits than another alpha character.完整的应用
import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.TextField;import javafx.scene.control.TextFormatter;import javafx.scene.layout.StackPane;import javafx.stage.Stage;public class JavaFXApplication149 extends Application{ @Override public void start(Stage primaryStage) { TextField textField = new TextField(); textField.setTextFormatter(new TextFormatter<>(c -> { if (c.getControlNewText().isEmpty()) { return c; } if (c.getControlNewText().matches("[A-z]") || c.getControlNewText().matches("[A-z]\d+") || c.getControlNewText().matches("[A-z]\d+[A-z]")) { return c; } else { return null; } })); StackPane root = new StackPane(textField); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); }}**更新:更改为
TextFormatter。@kleopatra表示这是实现此目标的正确方法。



