-1

I have a JtextArea in which I have to append text and I want it to scroll down when appending new text. I have done the following but it doesn't work.

showFrame = new JFrame("Gui Console");


    showArea = new JTextArea();

        showArea.setBorder(new TitledBorder("Console"));
        showArea.setPreferredSize(new Dimension(500, 400));
        showArea.setMinimumSize(new Dimension(500, 400));
        showArea.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
        showArea.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                JScrollBar vertical = scrollPane.getVerticalScrollBar();
                scrollPane.getVerticalScrollBar().setValue( vertical.getMaximum() );;

            }

            public void removeUpdate(DocumentEvent e) {

            }

            public void changedUpdate(DocumentEvent e) {

            }

        });

The only way that works is to set

showArea.setPreferredSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));

but the window becomes too big and I don't want it.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
M4tt3
  • 55
  • 2
  • 9
  • 2
    http://stackoverflow.com/questions/1627028/how-to-set-auto-scrolling-of-jtextarea-in-java-gui – kiheru Nov 22 '13 at 16:33
  • Don't use any of the setPreferred/Minimum/Maximum size methods. The text area will automatically recalculate the preferred size as text is appended. – camickr Nov 22 '13 at 17:01

3 Answers3

1
DefaultCaret caret = (DefaultCaret)yourTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
Alex
  • 1,100
  • 1
  • 9
  • 23
0

try this...

JScrollPane scrollPane = new JScrollPane(showArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500, 400));
add(scrollPane);

this is may help you. and scrollPane is add with JFrame or JPanel. no need to showArea

subash
  • 3,116
  • 3
  • 18
  • 22
0

You just need to put your JTextArea in a JScrollPane

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Test extends JFrame {

    public Test() {
        super("Test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JTextArea text = new JTextArea(5,20);
        text.setWrapStyleWord(true);
        text.setLineWrap(true);

        JScrollPane jsp = new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        add(jsp);

        pack();

        setVisible(true);

    }

    public static void main(String[] args) {

        new Test();

    }

}

Hope that helps, Salam

BilalDja
  • 1,072
  • 1
  • 9
  • 17