问题
So the first and last input should be letters, and between them should be only numbers. Here is my code :
tf.textProperty().addListener(new ChangeListener<String>() {
public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
String text_of_first_letter = tf.getText().substring(0, 1);
if (tf.getText().length() > 1 ) {
if(!newValue.matches("\\d*")) {
tf.setText(newValue.replaceFirst("[^\\d]", ""));
}
}
else if(tf.getText().length() == 1){
System.out.println("ktu");
tf.setText(newValue.replaceFirst("[^\\d]", text_of_first_letter));
}
}
});
回答1:
You can use TextFormatter and String's matches.
If the text in the TextField does not meet one of these three Regex, then show the old text.
case 1: newVal.matches("[A-z]") -> Single alpha character
case 2: newVal.matches("[A-z]\\d+") -> Alpha character followed by digits
case 3: newVal.matches("[A-z]\\d+[A-z]") -> Alpa character followed by digits than another alpha character.
Full app
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;
/**
*
* @author blj0011
*/
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();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
**Update: Change to TextFormatter. @kleopatra said it's the correct way to achieve this.
来源:https://stackoverflow.com/questions/49571994/hello-i-want-to-create-a-javafx-textfield-where-the-user-can-only-input-in-the