Auto scroll down a TextArea

2020-03-31 03:08发布

I have a TextArea that doesn't scroll down when I add text in it. I thought using this answer, but my TextArea is connected to a StringProperty like this :

consoleTextArea.textProperty().bind(textRecu);

So the answer doesn't work for me, is there another way to make my TextArea scroll down every time I update it by the binding?

1条回答
Animai°情兽
2楼-- · 2020-03-31 03:46

Here is fast demo of what i meant in comment about adding listener to the textRecu. Yep consoleTextArea.textProperty() can't be changed because of a binding. But textRecu has no binding => can be changed and we can add listener to it.

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
    private StringProperty textRecu = new SimpleStringProperty();
    private TextArea consoleTextArea = new TextArea();

    @Override
    public void start(Stage primaryStage) throws Exception{
        VBox root = new VBox();

        Button button = new Button("Add some text");
        button.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                //here you change textRecu and not consoleTextArea.textProperty()
                textRecu.setValue(textRecu.getValue() +"New Line\n");
            }
        });

        root.getChildren().addAll(consoleTextArea, button);
        consoleTextArea.textProperty().bind(textRecu);

        //here you also add listener to the textRecu 
        textRecu.addListener(new ChangeListener<Object>() {
            @Override
            public void changed(ObservableValue<?> observable, Object oldValue,
                                Object newValue) {
                // from stackoverflow.com/a/30264399/1032167
                // for some reason setScrollTop will not scroll properly
                //consoleTextArea.setScrollTop(Double.MAX_VALUE);
                  consoleTextArea.selectPositionCaret(consoleTextArea.getLength()); 
                  consoleTextArea.deselect(); 
            }
        });

        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


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

enter image description hereenter image description here

查看更多
登录 后发表回答