如何在追加后自动向下滚动JTextArea? [英] How to auto scroll down JTextArea after append?

查看:162
本文介绍了如何在追加后自动向下滚动JTextArea?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用JTextArea创建了一个JFrame。我想在每次追加后自动向下滚动textarea。我该如何管理?

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?

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

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

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");
    }
}


推荐答案

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

there are two ways (but JTextArea must be placed in JScrollPane)

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

a) set Caret (correct of ways)

例如


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


b)移动 JScrollBar (来自 JScrollPane )到其最大值

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

这篇关于如何在追加后自动向下滚动JTextArea?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆