问题描述
我有一个 TextArea
,当我在其中添加文字时,不会向下滚动。我想过使用,但我的 TextArea
连接到 StringProperty
,如下所示:
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);
所以答案对我不起作用,还有另外一种方法使我的 TextArea
通过绑定向下滚动每次更新
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?
推荐答案
以下是关于将监听器添加到textRecu的评论的快速演示。是的,因为绑定,无法更改consoleTextArea.textProperty()。但textRecu没有绑定=>可以更改,我们可以添加监听器。
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);
}
}
这篇关于自动向下滚动TextArea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!