写了一个简单的聊天室程序,
使用TextArea显示聊天内容,把他放在Jscrollpane中,可以显示滚动条
问题就是,当我发送了多条信息之后,
例如:我的TextArea只能显示8条数据,如果有10条数据时,数据始终从第1条显示到第8条,
要自己手动拖动滚动条,这样很不方便。
如何让TextArea显示我最新的消息?
不知道我表达清楚了没有,谢谢大家!
使用TextArea显示聊天内容,把他放在Jscrollpane中,可以显示滚动条
问题就是,当我发送了多条信息之后,
例如:我的TextArea只能显示8条数据,如果有10条数据时,数据始终从第1条显示到第8条,
要自己手动拖动滚动条,这样很不方便。
如何让TextArea显示我最新的消息?
不知道我表达清楚了没有,谢谢大家!
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollpane.getVerticalScrollBar()
.setValue(scrollpane.getVerticalScrollBar()
.getMaximum());
}
});
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();
}
}