本帖最后由 caoxulei 于 2010-12-04 23:30:25 编辑

解决方案 »

  1.   

    下面是界面以及处理的类package com.caoxulei;
    import javax.swing.*;
    import java.io.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;import javax.swing.JFrame;public class ChatJFrame extends JFrame implements ActionListener {
             private JTextArea text_receiver;
             private JTextField text_sender;
             private PrintWriter cout;
             private String name;
    public  ChatJFrame(String name, String title,PrintWriter cout) {
    // TODO 自动生成构造函数存根
    super("聊天室"+name +" "+title);
    this.setSize(320, 240);
    this.setLocation(300, 240);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.text_receiver= new JTextArea();
    this.text_receiver.setEditable(false);
    this.add(this.text_receiver);
    JPanel panel=new JPanel();
    this.add(panel,"South");
    this.text_sender=new JTextField(12);
    panel.add(this.text_sender);
    this.text_sender.addActionListener(this);
    JButton button_send=new JButton("发送");
    panel.add(button_send);
    button_send.addActionListener(this);
    JButton button_leava =new JButton("离线");
    panel.add(button_leava);
    button_leava.addActionListener(this);
    this.setVisible(true);
    this.setWriter(cout);
    this.name=name;
    }
        public void setWriter(PrintWriter cout) {
         this.cout=cout;

    }
        public void receive(String message) {
         text_receiver.append(message+"\r\n");
    }
        
    public void actionPerformed(ActionEvent e) {
    // TODO 自动生成方法存根
         if (e.getActionCommand()=="离线")
         {
          if (this.cout!=null){
          this.cout.println(name+"离线");
          this.cout.print("bye");
          this.cout=null;
          }
          text_receiver.append("我离线\n");
         }
         else{
          if (this.cout!=null){
          this.cout.println(name+"说:"+text_sender.getText());
          text_receiver.append("我说:"+text_sender.getText()+"\n");
          text_sender.setText("");
          }
          else 
          text_receiver.append("已离线,不能发送信息。\n");
         }
    }
    }
      

  2.   

    再学习一下NAT打洞技术,就好用了