写了一个简单的聊天室程序,
  使用TextArea显示聊天内容,把他放在Jscrollpane中,可以显示滚动条
  问题就是,当我发送了多条信息之后,
  例如:我的TextArea只能显示8条数据,如果有10条数据时,数据始终从第1条显示到第8条,
  要自己手动拖动滚动条,这样很不方便。
  如何让TextArea显示我最新的消息?
  不知道我表达清楚了没有,谢谢大家!

解决方案 »

  1.   

    多年前有朋友问过这个问题,也有朋友解答了这个问题,我粘过来给你看看是否能解决:在插入文本以后写下面的代码:   
        
      SwingUtilities.invokeLater(new   Runnable()   {   
        
                public   void   run()   {   
                          
        scrollpane.getVerticalScrollBar()   
            .setValue(scrollpane.getVerticalScrollBar()   
                                                       .getMaximum());   
      }   
      });  
      

  2.   

    package test;import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.Timer;public class AutoScrollTest {
      public static void main(String[] args) {
        final JTextArea textArea = new JTextArea();
        final JScrollPane scrollPane = new JScrollPane(textArea);
        JFrame f = new JFrame();
        f.getContentPane().add(scrollPane, BorderLayout.CENTER);
        f.setSize(400, 300);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        Timer timer = new Timer(500, new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            textArea.append(System.currentTimeMillis() + "\n");
            textArea.setCaretPosition(textArea.getDocument().getLength() - 1);
            // 或者用下面的方法
            // int lineCount = textArea.getLineCount();
            // try {
            // int pos = textArea.getLineStartOffset(lineCount-1);
            // Rectangle rect = textArea.modelToView(pos);
            // textArea.scrollRectToVisible(rect);
            // } catch (BadLocationException ex) {
            // ex.printStackTrace();
            // }
          }
        });
        timer.start();
      }
    }