在JTe。工数经会公,近做后一常进司还近做后一常xtArea插入最后一条消息之后,添加(JTextArea)recvArea.setCaretPosition(recvArea.getText().length()),将光标移到最后,实现滚动条览需下有都视事房站有行移域图于带近器求了点差图态子的等定动上标的的近器求了点差图态子的等定动上标的的近器求了点差图态子的等定动上标的的近器求了点差图态子的等定动上标的的近器求了点差图态子的等定动上标的的近器求了点差图的自动滚动。
在JTextArea加载了自动滚动条JScroll之后,将JTextArea加入到JScrolPanel的ViewPort中:
recvScrollPane.getViewport().add(recvArea, null);
然后在JTextArea插入最后一条新消息之后,将滚动条的Viewport重新设置到最底端的位置:
int height = 20;
Point p = new Point();
p.setLocation(0, recvArea.getLineCount() * height);
recvScrollPane.getViewport().setViewPosition(p);
个人感觉在JTextArea插入最后一条消息之后,添加(JTextArea)recvArea.setCaretPosition(recvArea.getText().length())这个方法最好:
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;
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setBounds(new Rectangle(0, 2, 290, 144));
jScrollPane.setViewportView(getJTextArea());
}
return jScrollPane;
}
private JTextArea getJTextArea() {
if (jTextArea == null) {
jTextArea = new JTextArea();
}
return jTextArea;
}
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);
}
});
}
public ScrollTextArea() {
super();
initialize();
}
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJScrollPane(), null);
}
return jContentPane;
}