user5455038
user5455038

Reputation:

JavaFX TextArea Limit

How do I set a limit on text area. I already made a counter that keeps track of the amount of characters in the text area, now I just need something to put in my if statement to make it impossible to put anymore text in the text area. How do I do that?

Upvotes: 0

Views: 7859

Answers (1)

James_D
James_D

Reputation: 209225

There's no point in creating a counter: the number of characters in the text area is already always available just from textArea.getText().length(), or, if you need an observable value, Bindings.length(textArea.textProperty()).

To limit the number of characters in a text area, set a TextFormatter which uses a filter that vetoes changes to the text if they would cause the text to exceed the maximum:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
import javafx.stage.Stage;

public class LimitedTextArea extends Application {

    @Override
    public void start(Stage primaryStage) {
        final int MAX_CHARS = 15 ;

        TextArea textArea = new TextArea();

        textArea.setTextFormatter(new TextFormatter<String>(change -> 
            change.getControlNewText().length() <= MAX_CHARS ? change : null));



        Scene scene = new Scene(textArea, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

Upvotes: 14

Related Questions