![](/img/trans.png)
[英]How to Disable TextArea Auto Scroll in JavaFX and Java 8?
[英]How to control the JavaFX TextArea auto scroll?
在我的应用程序中,我每2分钟将文本追加到TextArea
。 每当我向TextArea
追加新行时,自动滚动就会自动向下移动。 但我想将滚动条保持在我保持滚动按钮的位置。 如何在JavaFX中进行操作。
logTextArea.appendText("Here i am appending text to text area"+"\n");
logTextArea.setScrollTop(Double.MIN_VALUE);
我尝试过此操作,但滚动会自动下降,但是我需要保持滚动条的选择位置,我不想自动下降。
我怎样才能做到这一点?
最直接的方法是记住插入符号的位置,并在它被appendText
或setText
移动后将其还原。
您可以按照以下方法进行操作:
int caretPosition = area.caretPositionProperty().get();
area.appendText("Here i am appending text to text area"+"\n");
area.positionCaret(caretPosition);
也许您可以只将一个changeListener添加到TextArea中,而它什么也不做,或者每次更改其中的文本时,它只会滚动到TextArea的顶部。
logTextArea.textProperty().addListener(new ChangeListener<Object>() {
@Override
public void changed(ObservableValue<?> observable, Object oldValue, Object newValue) {
logTextArea.setScrollTop(Double.MIN_VALUE); //this will scroll to the top
}
});
现在,当您使用logTextArea.appendText("Here i am appending text to text area"+"\\n");
到TextArea,它应该位于顶部。
这个想法来自: JavaFX TextArea和autoscroll
您可以编写自己的函数来附加文本。 在此方法中,可以使用setText
,而不是appendText
因为appendText
自动滚动到内容的末尾( setText
滚动到内容的开头,但是可以通过将scrollTopProperty
设置回其先前的值来抑制它)。
例
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
TextArea ta = new TextArea();
root.setCenter(ta);
Button button = new Button("Append");
button.setOnAction(e -> {
appendTextToTextArea(ta, "BlaBlaBla\n");
});
root.setBottom(button);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
/**
* Appends text to the end of the specified TextArea without moving the scrollbar.
* @param ta TextArea to be used for operation.
* @param text Text to append.
*/
public static void appendTextToTextArea(TextArea ta, String text) {
double scrollTop = ta.getScrollTop();
ta.setText(ta.getText() + text);
ta.setScrollTop(scrollTop);
}
}
注意:
另外,您还可以扩展TextArea
和重载appendText
来指定是否要移动滚动条:
public class AppendableTextArea extends TextArea {
public void appendText(String text, Boolean moveScrollBar) {
if (moveScrollBar)
this.appendText(text);
else {
double scrollTop = getScrollTop();
setText(getText() + text);
setScrollTop(scrollTop);
}
}
}
和用法:
AppendableTextArea ta = new AppendableTextArea();
ta.appendText("BlaBlaBla\n", false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.