あなたがテキストを追加するために、独自の関数を書くことができます。この方法では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