How to limit the amount of characters a javafx textfield
Asked Answered
A

8

12

I´m using a FXML to set my form, but I need to set the limit of characters in textfields. How can I made this ?

Avens answered 28/3, 2014 at 13:29 Comment(0)
O
5

Here is my solution to limit the length of a textfield. I would not recommend solutions which use a listener (on text property or on length property), they do not behave correctly in all situations (for what I have seen). I create an HTML input text with a max length, and compare it to my textfield in JavaFX. I had the same behavior with paste operations (Ctrl + V), cancel operations (Ctrl + Z) in both cases. The goal here is to check if the text is valid BEFORE modifying the textfield. We could use a similar approach for a numeric text field.

import java.util.Objects;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.control.TextField;   

public class LimitedTextField extends TextField {

    private final IntegerProperty maxLength;

    public LimitedTextField() {
        super();
        this.maxLength = new SimpleIntegerProperty(-1);
    }

    public IntegerProperty maxLengthProperty() {
        return this.maxLength;
    }

    public final Integer getMaxLength() {
        return this.maxLength.getValue();
    }

    public final void setMaxLength(Integer maxLength) {
        Objects.requireNonNull(maxLength, "Max length cannot be null, -1 for no limit");
        this.maxLength.setValue(maxLength);
    }

    @Override
    public void replaceText(int start, int end, String insertedText) {
        if (this.getMaxLength() <= 0) {
            // Default behavior, in case of no max length
            super.replaceText(start, end, insertedText);
        }
        else {
            // Get the text in the textfield, before the user enters something
            String currentText = this.getText() == null ? "" : this.getText();

            // Compute the text that should normally be in the textfield now
            String finalText = currentText.substring(0, start) + insertedText + currentText.substring(end);

            // If the max length is not excedeed
            int numberOfexceedingCharacters = finalText.length() - this.getMaxLength();
            if (numberOfexceedingCharacters <= 0) {
                // Normal behavior
                super.replaceText(start, end, insertedText);
            }
            else {
                // Otherwise, cut the the text that was going to be inserted
                String cutInsertedText = insertedText.substring(
                        0, 
                        insertedText.length() - numberOfexceedingCharacters
                );

                // And replace this text
                super.replaceText(start, end, cutInsertedText);
            }
        }
    }
}

Tested with JavaFX 8 and Java 8u45

Ornstead answered 1/7, 2015 at 12:36 Comment(0)
K
17

You can't directly set a limit to number of characters. But you can add a listener to lengthProperty() of the textfield

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TextFieldLimit extends Application {
    private static final int LIMIT = 10;

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

    @Override
    public void start(final Stage primaryStage) {

        final TextField textField = new TextField();
        textField.lengthProperty().addListener(new ChangeListener<Number>() {

            @Override
            public void changed(ObservableValue<? extends Number> observable,
                    Number oldValue, Number newValue) {
                if (newValue.intValue() > oldValue.intValue()) {
                    // Check if the new character is greater than LIMIT
                    if (textField.getText().length() >= LIMIT) {

                        // if it's 11th character then just setText to previous
                        // one
                        textField.setText(textField.getText().substring(0, LIMIT));
                    }
                }
            }
        });

        VBox vbox = new VBox(20);
        vbox.getChildren().add(textField);

        Scene scene = new Scene(vbox, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
Karajan answered 28/3, 2014 at 18:27 Comment(1)
I'd recommend textField.setText(textField.getText().substring(0, LIMIT));. Otherwise if the user uses copy and paste to dump a very large string in there, it'll repeatedly invoke the listener, reducing the text one character at a time.Subminiaturize
O
5

Here is my solution to limit the length of a textfield. I would not recommend solutions which use a listener (on text property or on length property), they do not behave correctly in all situations (for what I have seen). I create an HTML input text with a max length, and compare it to my textfield in JavaFX. I had the same behavior with paste operations (Ctrl + V), cancel operations (Ctrl + Z) in both cases. The goal here is to check if the text is valid BEFORE modifying the textfield. We could use a similar approach for a numeric text field.

import java.util.Objects;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.control.TextField;   

public class LimitedTextField extends TextField {

    private final IntegerProperty maxLength;

    public LimitedTextField() {
        super();
        this.maxLength = new SimpleIntegerProperty(-1);
    }

    public IntegerProperty maxLengthProperty() {
        return this.maxLength;
    }

    public final Integer getMaxLength() {
        return this.maxLength.getValue();
    }

    public final void setMaxLength(Integer maxLength) {
        Objects.requireNonNull(maxLength, "Max length cannot be null, -1 for no limit");
        this.maxLength.setValue(maxLength);
    }

    @Override
    public void replaceText(int start, int end, String insertedText) {
        if (this.getMaxLength() <= 0) {
            // Default behavior, in case of no max length
            super.replaceText(start, end, insertedText);
        }
        else {
            // Get the text in the textfield, before the user enters something
            String currentText = this.getText() == null ? "" : this.getText();

            // Compute the text that should normally be in the textfield now
            String finalText = currentText.substring(0, start) + insertedText + currentText.substring(end);

            // If the max length is not excedeed
            int numberOfexceedingCharacters = finalText.length() - this.getMaxLength();
            if (numberOfexceedingCharacters <= 0) {
                // Normal behavior
                super.replaceText(start, end, insertedText);
            }
            else {
                // Otherwise, cut the the text that was going to be inserted
                String cutInsertedText = insertedText.substring(
                        0, 
                        insertedText.length() - numberOfexceedingCharacters
                );

                // And replace this text
                super.replaceText(start, end, cutInsertedText);
            }
        }
    }
}

Tested with JavaFX 8 and Java 8u45

Ornstead answered 1/7, 2015 at 12:36 Comment(0)
E
5

One more elegance solution

Pattern pattern = Pattern.compile(".{0,25}");
    TextFormatter formatter = new TextFormatter((UnaryOperator<TextFormatter.Change>) change -> {
        return pattern.matcher(change.getControlNewText()).matches() ? change : null;
    });

    textField.setTextFormatter(formatter);

where 0 and 25 - min and max amount of chars. + ability to set a pattern of input text

Exine answered 20/8, 2018 at 14:35 Comment(0)
S
1

This is a very simple solution that seems to work for me.

textfield.setOnKeyTyped(event ->{
        int maxCharacters = 5;
        if(tfInput.getText().length() > maxCharacters) event.consume();
    });
Schilit answered 17/11, 2017 at 21:24 Comment(0)
L
1

I use a simple call to ChangeListener, where I test the condition to perform stops.

textFild.addListener((observable, oldValue, newValue) -> {
    if (newValue.length() == MAX_SIZE) {
        textField.setText(oldValue);
    }
});
Lease answered 18/11, 2017 at 3:51 Comment(0)
A
0

This is a better way to do the job on a generic text field:

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);
            }
        }
    });
}

Works perfectly, except for that Undo bug.

Alkylation answered 30/6, 2017 at 10:37 Comment(0)
E
0

the following 1-liner will exactly do it, wheras 5 is the limit of the TextField tf:

tf.setTextFormatter(new TextFormatter<>(c -> c.getControlNewText().matches(".{0,5}") ? c : null));
Elasticity answered 8/5, 2021 at 0:56 Comment(0)
G
-1

This is a solution that works well:

@FXML
void limitTextFields(KeyEvent event) {
    int maxLength = 5;
    TextField tf = (TextField) event.getSource();
    if (tf.getText().length() > maxLength) {
        tf.deletePreviousChar();
    }
}
Guanine answered 25/6, 2021 at 7:34 Comment(1)
no (you would limit only on direct typing, not on pasting f.i.), use a textFormatter insteadIsopleth

© 2022 - 2024 — McMap. All rights reserved.