源码import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class Client {
private JFrame frame;
private JTextArea jta;
private JTextField jtf;
private Socket s;
private BufferedReader in;
private PrintWriter out;
private String strIP="";
private JButton jb;
public void init(){
/*
 * 命令行键入IP地址
 */


try{
BufferedReader in = new BufferedReader
(new InputStreamReader(System.in));
System.out.print("请输入IP地址 >");
strIP = in.readLine();
}catch(IOException e){
e.printStackTrace();
}


/*
 * 客户端界面
 */
frame=new JFrame("聊天程序客户端");
frame.setSize(400,250);
jta=new JTextArea();
jta.setEditable(false);
    jta.setAutoscrolls(true);
    
    
frame.add(new JScrollPane(jta));

jtf=new JTextField();
frame.add(jtf,"South");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
/*
 * 从键盘获取IP地址,端口为9000,创建客户端。
 */
try {
s=new Socket(strIP,9000);
out=new PrintWriter(s.getOutputStream());
in=new BufferedReader(
new InputStreamReader(
s.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
/*
 * 添加文本输入监听,把输入的内容显示
 */
jtf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String text=jtf.getText();
jtf.setText("");
out.println(text);
out.flush();
}
});
}
/*
 *显示聊天内容格式
 */
private void receiveText(){
try {
while(true){
String str=in.readLine();
jta.append(str+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public Client(){
init();
receiveText();
}
public static void main(String[] args) {

new Client();
}}

解决方案 »

  1.   


    class TextAreaScroller extends ComponentAdapter{
        public void componentResized(ComponentEvent event){
            int lastLine = jta.getLineCount()-1;
            int lineTop = jta.getRowHeight()*lastLine;
            JScrollPane jsp = (JScrollPane)SwingUtilities.getAncestorofClass(JScrollPane.class,jta);
            JViewport jvp = jsp.getViewport();
            int portHeight = jvp.getSize().height;
            int position = lineTop - (portHeight - jta.getRowHeight());
            if(position > = 0)
                jvp.setViewPosition(new Point(0,position));
        }
    }然后把jta放到JScrollPane中
    jta.addComponentListener(new TextAreaScroller ());