您可以编写自己的功能,将文本追加。在此方法中,您可以使用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);
我需要添加这个吗?是指类控制器类或应用程序扩展类@ user2882590 – epn
您有一个控制器类,您声明了TextArea。如果我没有记错,在'public void initialize()'函数中,如果来自fxml文件,可以将此侦听器添加到'logTextArea'中。如果没有,那么你可以在创建它之后添加这个监听器。所以之后:'TextArea logTextArea = new TextArea();' – sundri23
好吧,但我的问题是添加一些文本到文本区域后,我滚动我的按钮到中间,之后,当我添加文本滚动按钮不会走上去需要留在中间只有我想那样。我能怎么做 ? – epn