(1)在JTextArea插入最后一条消息之后,使用selectAll()将光标强制移动到JTextArea的最后,实现滚动条的自动滚动。(Aviva中采用的方式)
(2)在JTextArea插入最后一条消息之后,使用(JTextArea)recvArea.setCaretPosition(recvArea.getText().length()),将光标移到最后,实现滚动条的自动滚动。 (3)在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); import java.awt.Rectangle; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; public class ScrollTextArea extends JFrame { private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JScrollPane jScrollPane = null; private JTextArea jTextArea = null; /** * This method initializes jScrollPane * * @return javax.swing.JScrollPane */ private JScrollPane getJScrollPane() { if (jScrollPane == null) { jScrollPane = new JScrollPane(); jScrollPane.setBounds(new Rectangle(0, 2, 290, 144)); jScrollPane.setViewportView(getJTextArea()); } return jScrollPane; } /** * This method initializes jTextArea * * @return javax.swing.JTextArea */ private JTextArea getJTextArea() { if (jTextArea == null) { jTextArea = new JTextArea(); } return jTextArea; } /** * @param args */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { ScrollTextArea thisClass = new ScrollTextArea(); thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); thisClass.setVisible(true); } }); } /** * This is the default constructor */ public ScrollTextArea() { super(); initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(300, 200); this.setContentPane(getJContentPane()); this.setTitle("JFrame"); } /** * This method initializes jContentPane * * @return javax.swing.JPanel */ private JPanel getJContentPane() { if (jContentPane == null) { jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(getJScrollPane(), null); } return jContentPane; } |
private void init()
{
setBounds(0, 0, 300, 150);
final JScrollPane sp = new JScrollPane(ta);
getContentPane().add(sp, "Center");
for (int i = 0; i <= 10; i++)
{
ta.append(i + "/n");
}
JScrollBar sb = sp.getVerticalScrollBar();
sb.setValue(sb.getMaximum());
// TimerTask task = new TimerTask(){
// public void run(){
// ta.append("Time: " + (System.currentTimeMillis() / 1000));
// scrollAndSetCursor();
// }
// };
}