Hello , I want to create a javafx TextField where the user can only input in the current order A11111111A [closed]

被刻印的时光 ゝ 提交于 2019-11-30 10:10:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!