p*a 发帖数: 592 | 1 经过痛苦的实践与摸索,偶终于找到了一个土办法让它滚动
到最后一行.
首先记录下空白JTextArea的viewport size
然后append一行文字进去,再记录新的viewport size
然后算出这两个size的高度差
然后取得JTextArea的vertical scrollbar
设其value为其maximum value+新添行数x高度差
code 如下:
// get line height first
JTextArea area=MyFrame.getTextArea();
Dimension d1=area.getPreferredScrollableViewportSize();
area.append(message); //one line message
Dimension d2=area.getPreferredScrollableViewportSize();
int lineHeight=(int)(d2.getHeight()-d1.getHeight());
......
// append new te | v***o 发帖数: 5 | 2 I had a trick long time ago, maybe not working now.
try setText("\r") first, then append. (or maybe setText("\r\n"))
scrolling the text shouldn't have been such a pain... |
|