osk
osk

Reputation: 810

JavaFX: How to restrict manipulation of TextArea to last row?

I am trying to simulate a shell using JavaFX. I want to handle both the output and input in the same TextArea, so I want to be able to edit and write to only the last row of the TextArea where the prompt is, just like a shell.

Any ideas on how to do this?

Upvotes: 1

Views: 965

Answers (1)

James_D
James_D

Reputation: 209225

You can subclass TextArea and prevent changes to the text if there are newlines after the point at which the edit occurs. According to Richard Bair's blog post, the only methods you need to override are replaceText() and replaceSelection.

Here is a quick example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class ConsoleTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setScene(new Scene(new BorderPane(new Console()), 600, 600));
        primaryStage.show();
    }

    public static class Console extends TextArea {
        @Override
        public void replaceText(int start, int end, String text) {
            String current = getText();
            // only insert if no new lines after insert position:
            if (! current.substring(start).contains("\n")) {
                super.replaceText(start, end, text);
            }
        }
        @Override
        public void replaceSelection(String text) {
            String current = getText();
            int selectionStart = getSelection().getStart();
            if (! current.substring(selectionStart).contains("\n")) {
                super.replaceSelection(text);
            }
        }
    }

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

If you want to display a prompt (which is not editable, of course), then the logic is a little trickier, but should be reasonably straightforward. You may also need some special handling for the case where the text parameter passed into those methods contains newlines.

Upvotes: 3

Related Questions