带有JTextAreas的JTabbedPane。自动向下滚动

时间:2016-06-29 15:07:21

标签: java swing jtextarea jtabbedpane

我有一个带有JTextAreas作为组件的JTabbedPane。使用另一种方法我将Texts添加到TextAreas。但是如果TextArea已满,它不会向下滚动,所以我看不到最新的文本。我该如何解决这个问题?

    public class View extends JFrame{

    public class Field extends JTextArea{
    public Field(){
        this.setEditable(false);
        this.setLineWrap(true);
        DefaultCaret caret = (DefaultCaret)this.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    }

}

    public View(){


    this.setLayout(new BorderLayout());
    this.tabs = new JTabbedPane();
    this.tabs.add("abc", new Field());

    this.add(tabs, BorderLayout.CENTER);

}
}

1 个答案:

答案 0 :(得分:2)

您需要将JTextArea置于JScrollPane内以使其可滚动:

import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;

public class Example {

    public static void main(String[] args) {

        JFrame jFrame = new JFrame();

        JTextArea textArea = new JTextArea();
        DefaultCaret caret = (DefaultCaret)textArea.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        JScrollPane jScrollPane = new JScrollPane(textArea);
        jScrollPane.setPreferredSize(new Dimension(300, 300));

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("abc", jScrollPane);

        jFrame.setContentPane(tabbedPane);

        jFrame.pack();
        jFrame.setVisible(true);

        for(int i = 0; i < 100; i ++) {
            textArea.append(i + "\n");
        }
    }
}