在JTextArea插入最后一条消息之后,添加(JTextArea)recvArea.setCaretPosition(recvArea.getText().length()),将光标移到最后,实现滚动条的自动滚动。 在JTextArea加载了自动滚动条JScroll之后,将JTextArea加入到JScrolPanel的ViewPort中:
个人感觉在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; } |