JavaFX TextArea限制

1 javafx

如何设置文本区域限制.我已经创建了一个计数器来跟踪文本区域中的字符数量,现在我只需要在if语句中添加一些内容,使其无法在文本区域中放置任何文本.我怎么做?

Jam*_*s_D 11

创建一个计数器是没有意义的:文本区域中的字符数已经始终可用textArea.getText().length(),或者,如果您需要一个可观察的值,Bindings.length(textArea.textProperty()).

要限制文本区域中的字符数,请设置TextFormatter使用过滤器的过滤器,如果它们会导致文本超出最大值,则会对文本进行更改:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)