0

I am looking for a simple solution to making first and last line of TextArea uneditable. enter image description here

As seen on the picture, I need to keep the first and last line, user can edit or input whatever he wants in the curly brackets. I have actually come up with this simple class, but it kinda breaks when user manages to get the closing curly bracket on the second line, leaving no lines between the first and the last one, rendering the user unable to edit anything.

Thanks for all responses.

public static class ScriptArea extends TextArea {
        @Override
        public void replaceText(int start, int end, String text) {
            String currentToStart = getText().substring(0, start);
            String startToEnd = getText().substring(start);
            if (currentToStart.contains("\n") && startToEnd.contains("\n")) {
                super.replaceText(start, end, text.equals("\n")?"\n\t":text);
            }
        }
    }
Poody
  • 325
  • 3
  • 13
  • `TextFlow` could be usefull. Check this [http://stackoverflow.com/questions/29974765/creating-a-large-body-of-text-with-different-styles-javafx-fxml](http://stackoverflow.com/questions/29974765/creating-a-large-body-of-text-with-different-styles-javafx-fxml) – jns Apr 16 '16 at 20:09

1 Answers1

2

Use a TextFormatter with a filter that vetoes any changes that don't leave the text in the correct form:

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 TextAreaFixedStartEndLines extends Application {

    private final String start = "function collideWith(mobj, tar, dir) {\n";
    private final String end = "\n}";

    @Override
    public void start(Stage primaryStage) {
        TextArea textArea = new TextArea();
        textArea.setTextFormatter(new TextFormatter<String>((Change c) -> {
            String proposed = c.getControlNewText();
            if (proposed.startsWith(start) && proposed.endsWith(end)) {
                return  c;
            } else {
                return null ;
            }
        }));

        textArea.setText(start+"\n"+end);

        primaryStage.setScene(new Scene(textArea, 600, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
James_D
  • 201,275
  • 16
  • 291
  • 322