【发布时间】:2021-10-17 19:24:00
【问题描述】:
我正在尝试在我的 TextField 上应用正则表达式模式,以便用户只能键入字符、数字和空格,但是我不希望开头有任何空格或数字。 (我不能只在输入后删除空格)。我使用下面的正则表达式和代码来实现这一点,但是一旦输入第一个字符,它就不能用退格键删除并永久保留在那里,而任何其他不在第一个位置的字符都可以退格。如何解决此问题并确保整个 TextField 可以退格?
我正在使用 javaFX 8。
import java.io.File;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class test extends Application{
@Override
public void start(Stage primaryStage) {
try{
TextField user = new TextField();
Pattern pattern = Pattern.compile("[a-zA-Z][a-zA-Z0-9 ]*");
UnaryOperator<TextFormatter.Change> filter = string -> {
if (pattern.matcher(string.getControlNewText()).matches()) {
return string ;
} else {
return null ;
}
};
TextFormatter<String> formatter = new TextFormatter<>(filter );
user.setTextFormatter(formatter);
//username submit button
Button submitButton = new Button("Submit");
//submit action for button
Label userPrompt = new Label("Enter name");
Stage stage = new Stage();
stage.setTitle("Username Entry");
VBox userEntry = new VBox(userPrompt,user , submitButton);
Scene scene1 = new Scene((userEntry),400,300);
stage.setScene(scene1);
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
【问题讨论】:
标签: java regex javafx javafx-8 textfield