Java Swing - how to scroll down a JTextArea?

2019-02-09 01:48发布

问题:

I have an application with basic chat. I use JTextArea for the buffer. After adding a message I want to scroll to the bottom. How can this be achieved?

I found no member function that would allow me to do this.

回答1:

You can do this by setting the caret position to the end of the text area, i.e.,

myTextArea.setCaretPosition(myTextArea.getDocument().getLength());

Edit: you can find out a lot more on this question by looking at the related questions listed on the lower right of this page. In particular, please check out camickr's answer and link in this thread: How to set AUTO-SCROLLING of JTextArea in Java GUI?. It's a far better and more complete answer than the one I've given (and I've just now up-voted it for this).