1. 利用JTextArea的selectAll();方法在添加信息之后强制将光标移动到最后一行。据说是Aviva中采用的方式。 2.使用JTextArea的setCaretPosition();手动设置光标的位置为最后一行。人气颇高。使用方法也很简单,如下:textArea.setCaretPosition(textArea.getDocument().getLength()); 3.(copy的)在JTextArea加载了自动滚动条JScroll之后,将JTextArea加入到JScrolPanel的ViewPort中: (有一些Bug,使得图像有点闪烁) recvScrollPane.getViewport().add(recvArea, null); 然后在JTextArea插入最后一条新消息之后,将滚动条的Viewport重新设置到最底端的位置: int height = 20; Point p = new Point(); p.setLocation(0, recvArea.getLineCount() * height); recvScrollPane.getViewport().setViewPosition(p); 4.网上以为仁兄用英文说的tricky treatment JTextPane pane = new JTextPane();... // add some text to the JTextPane... Document doc = pane.getDocument(); pane.select(doc.getLength(), doc.getLength()); // this should enforce the viewport move to where the line being selected. ... 5.这似乎是最常用的方法,但是实际使用情况是只能到倒数第二行。 JScrollBar sbar=spContainer.getVerticalScrollBar(); sbar.setValue(sbar.getMaximum());
tx.setCaretPosition(tx.getText().length());
我试了你写的tx.setCaretPosition(tx.getText().length());
可以让JScrollPane中滚动条始终在最下面
2.使用JTextArea的setCaretPosition();手动设置光标的位置为最后一行。人气颇高。使用方法也很简单,如下:textArea.setCaretPosition(textArea.getDocument().getLength());
3.(copy的)在JTextArea加载了自动滚动条JScroll之后,将JTextArea加入到JScrolPanel的ViewPort中: (有一些Bug,使得图像有点闪烁)
recvScrollPane.getViewport().add(recvArea, null);
然后在JTextArea插入最后一条新消息之后,将滚动条的Viewport重新设置到最底端的位置:
int height = 20;
Point p = new Point();
p.setLocation(0, recvArea.getLineCount() * height);
recvScrollPane.getViewport().setViewPosition(p);
4.网上以为仁兄用英文说的tricky treatment
JTextPane pane = new JTextPane();... // add some text to the JTextPane...
Document doc = pane.getDocument();
pane.select(doc.getLength(), doc.getLength()); // this should enforce the viewport move to where the line being selected.
...
5.这似乎是最常用的方法,但是实际使用情况是只能到倒数第二行。
JScrollBar sbar=spContainer.getVerticalScrollBar();
sbar.setValue(sbar.getMaximum());