Java 追加后如何自动向下滚动JTextArea?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23365847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:16:25  来源:igfitidea点击:

How to auto scroll down JTextArea after append?

javaswingjtextarea

提问by Iter Ator

I've created a JFrame, with a JTextArea. I would like to scroll down the textarea automatically, after each append. How should I manage it?

我创建了一个带有 JTextArea 的 JFrame。我想在每次追加后自动向下滚动文本区域。我应该如何管理它?

I've tried log.setCaretPosition(log.getDocument().getLength());, but nothing changed.

我试过了log.setCaretPosition(log.getDocument().getLength());,但没有任何改变。

package scrollit;

import java.awt.*;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;

public class ScrollIt extends JFrame {    

    public static void main(String[] args) {            
        ScrollIt sc = new ScrollIt();            
    }

    public ScrollIt() {
        super();            
        JTextArea log = new JTextArea();
        log.setPreferredSize(new Dimension(50,50));
        setDefaultCloseOperation(EXIT_ON_CLOSE);            
        add(log);            
        pack();
        setVisible(true);

        log.append("a\n");
        log.append("b\n");
        log.append("c\n");
        log.append("d\n");
        log.append("e\n");
        log.append("f\n");
    }
}

采纳答案by mKorbel

there are two ways (but JTextAreamust be placed in JScrollPane)

有两种方式(但JTextArea必须放在JScrollPane 中

a) set Caret(correct of ways)

a)设置插入符号(正确的方式)

e.g.

例如

  DefaultCaret caret = (DefaultCaret) log.getCaret();
  caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  DefaultCaret caret = (DefaultCaret) log.getCaret();
  caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

b) moving with JScrollBar(from JScrollPane) to its max value

b) 随着JScrollBar(from ) 移动JScrollPane到它的最大值

回答by user3498796

Mine is a little simpler and efficient. We set the caret to the length of the text to put it at the end like so.

我的有点简单和高效。我们将插入符号设置为文本的长度以将其放在最后。

public void appendText(String str){
    txtArea.append(str + "\n");
    scrollDown();
}

public void scrollDown(){
    txtArea.setCaretPosition(txtArea.getText().length());
}