Search code examples
javajavafx-2javafxjavafx-8

How to use JavaFX TextField maxlength


How to use this code in my main class of JavaFX so that I can set maxlength of characters in JavaFX TextField?

class LimitedTextField extends TextField {

    private final int limit;

    public LimitedTextField(int limit) {
        this.limit = limit;
    }

    @Override
    public void replaceText(int start, int end, String text) {
        super.replaceText(start, end, text);
        verify();
    }

    @Override
    public void replaceSelection(String text) {
        super.replaceSelection(text);
        verify();
    }

    private void verify() {
        if (getText().length() > limit) {
            setText(getText().substring(0, limit));
        }

    }
};

My JavaFX main class is given below:

public class TextFiled extends Application {
    @Override
    public void start(Stage primaryStage) {
        final TextField t_fname = new TextField();
        
        StackPane root = new StackPane();
        root.getChildren().add(t_fname);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Solution

  • This is my solution:

    public static void addTextLimiter(final TextField tf, final int maxLength) {
        tf.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(final ObservableValue<? extends String> ov, final String oldValue, final String newValue) {
                if (tf.getText().length() > maxLength) {
                    String s = tf.getText().substring(0, maxLength);
                    tf.setText(s);
                }
            }
        });
    }
    

    See JavaFX 2.2 TextField maxlength and Prefer composition over inheritance?