⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatarea.java~2~

📁 1. 消息即时通信 2. 消息发送实现一对一、一对多等多种发送模式 3. 发送的消息实现多彩文本编辑
💻 JAVA~2~
字号:
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.text.*;
import java.net.*;

public class ChatArea extends JPanel implements Runnable{
  BorderLayout borderLayout1 = new BorderLayout();
  Action action=new Action();
  FileDisposeButton fb;//=new FileDisposeButton("dd","ok","12.",2560);
  static LoginDialog loginDialog=new LoginDialog();
  JFileChooser chooser=new JFileChooser();

  JButton jButton1 = new JButton();
  JMenuBar jmenuBar=new JMenuBar();
  JMenu loginMenu=new JMenu();
  JMenu fileMenu=new JMenu();
  JMenuItem login=new JMenuItem();
  JMenuItem loginOut=new JMenuItem();
  JMenuItem sendFile=new JMenuItem();
  static JTextPane publicChat=new JTextPane();
  static JTextPane privateChat=new JTextPane();

  static Document publicChatDocument=publicChat.getDocument();
  static Document privateChatDocument=privateChat.getDocument();
  static MutableAttributeSet char_style=new SimpleAttributeSet();
  String[] items = {"大家"};
  DefaultListModel model = new DefaultListModel();
  JList peopleList=new JList(items);




  JScrollPane comjscrollPane=new JScrollPane(publicChat);
  JScrollPane perjscrollPane=new JScrollPane(privateChat);
  JScrollPane listPane=new JScrollPane(peopleList);
  JSplitPane jsplitPane1=new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                        comjscrollPane,perjscrollPane);
  JSplitPane jsplitPane2=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                                        listPane,jsplitPane1);

  JPanel jpanel1=new JPanel();
  JPanel jpanel2=new JPanel();
  JPanel jpanel3=new JPanel();
  JPanel jpanel4=new JPanel();
  JPanel jpanel5=new JPanel();

  JTextField messageField=new JTextField(40);
  JButton sendMessageButton=new JButton();
  //JButton agreeButton=new JButton();
  //JButton otherSaveButton=new JButton();
 // JButton disagreeButton=new JButton();
  JButton clearSendObjectButton=new JButton();


  static JLabel sendObject=new JLabel("                                      ");

  File file=null;
  static Hashtable peopleTable=new Hashtable();
  static DataOutputStream out=null;
  DataInputStream in=null;
  static Socket socket=null;
  Thread messageThread=null;

  Vector toPeople=new Vector();
  String selectName="";
  StringBuffer selectNameSB=new StringBuffer();
  String peoples="";


  public ChatArea(Hashtable peopleTable) {
  this.peopleTable=peopleTable;
    try {
      jbInit();
    }
    catch(Exception ex) {
      ex.printStackTrace();
    }
  }
  void jbInit() throws Exception {

    peopleList.setModel(model);
    publicChat.setEditable(false);
    privateChat.setEditable(false);
    jButton1.setText("jButton1");
    loginDialog.setVisible(true);
    loginMenu.setText("登陆");
    fileMenu.setText("文件");
    login.setText("登陆");
    loginOut.setText("退出");
    sendFile.setText("发送文件");


    jmenuBar.add(loginMenu);
    jmenuBar.add(fileMenu);
    loginMenu.add(login);
    loginMenu.add(loginOut);
    fileMenu.add(sendFile);
    jsplitPane1.setDividerSize(12);
    jsplitPane1.setOneTouchExpandable(true);
    jsplitPane2.setDividerSize(12);
    jsplitPane2.setOneTouchExpandable(true);

    sendMessageButton.setText("发送");
    //agreeButton.setText("保存");
    //disagreeButton.setText("拒绝");
    //otherSaveButton.setText("另存为");
    clearSendObjectButton.setText("清除选定对像");



    jpanel1.setLayout(new GridLayout(1,2));
    jpanel2.setLayout(new FlowLayout());
    //jpanel3.setLayout(new GridLayout(1,2));
    //jpanel4.setLayout(new GridLayout(1,3));
    jpanel5.setLayout(new GridLayout(2,1));

    jpanel1.add(jpanel2);
    jpanel1.add(jpanel5);

    jpanel2.add(messageField);

    jpanel3.setLayout(new BorderLayout());
    jpanel3.add(sendMessageButton,BorderLayout.WEST);
    jpanel3.add(sendObject,BorderLayout.CENTER);
    jpanel3.add(clearSendObjectButton,BorderLayout.EAST);
    //jpanel4.add(fb);
    //jpanel4.add(disagreeButton);
    //jpanel4.add(otherSaveButton);

    jpanel5.add(jpanel3);
    jpanel5.add(jpanel4);


   // jsplitPane.setLocation(20,20);
    this.setLayout(borderLayout1);
    this.add(jmenuBar, BorderLayout.NORTH);
    this.add(jsplitPane2,BorderLayout.CENTER);
    this.add(jpanel1,BorderLayout.SOUTH);
    //this.add(listPane,BorderLayout.EAST);
    login.addActionListener(action);
    loginOut.addActionListener(action);
    sendFile.addActionListener(action);
    sendMessageButton.addActionListener(action);
    //agreeButton.addActionListener(action);
    //disagreeButton.addActionListener(action);
   // otherSaveButton.addActionListener(action);
    clearSendObjectButton.addActionListener(action);

    peopleList.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent me){
      JList list = (JList)me.getSource();
      if(me.getClickCount()==1){
        selectName= (String) peopleList.getSelectedValue();
        if(!toPeople.contains(selectName)){
          toPeople.addElement(selectName);
          selectNameSB.append(selectName+"  ");
        }
        //Enumeration enum=toPeople.elements();
        ChatArea.sendObject.setText(selectNameSB.toString());
      }
    }
    });

     messageThread=new Thread(this);


    peopleList.setToolTipText("单击,选择聊天或者发送文件的对象");
    sendObject.setToolTipText("选定的聊天对象");
    clearSendObjectButton.setToolTipText("清空选定的对象");


  }
  public void setConnection(Socket socket,DataOutputStream out,DataInputStream in){
    this.socket=socket;
    this.out=out;
    this.in=in;
    /*try{
      this.in = new DataInputStream(this.socket.getInputStream());
    }catch(Exception e){

    }*/
    try{
      //System.out.println(socket.getLocalPort()+"chatarea");

      messageThread.start();

    }catch(Exception e){
      e.printStackTrace();
    }
  }
  public static Socket getSocket(){  return socket;  }
  public static DataOutputStream getOut(){ return out;}

  public void run(){
    String _message=null;
    //byte[] buffer=new byte[256];
    while(true){
      try{
        //System.out.println(this.socket.getPort());
        //if(in!=null){
        // System.out.println("runing");
       // }
        //if(in.readInt()!=-1){
          //System.out.println(in.readUTF());
        //}
       // System.out.println("try");
        _message=in.readUTF();
       // if(_message.length()>0){
        //  System.out.println(_message);
         if (_message.startsWith("PRIVATE_MESSAGE:")) {

            String content = _message.substring(_message.indexOf(
                "PRIVATEMESSAGE:") + 17);
            try {
              privateChatDocument.insertString(privateChatDocument.getLength(),
                                               content + "\n", char_style);

            }
            catch (BadLocationException e) {
              e.printStackTrace();
            }
          }
          else if (_message.startsWith("PUBLIC_MESSAGE:")) {
            String content = _message.substring(_message.indexOf(
                "PUBLIC_MESSAGE:") + 15);
            try {
              publicChatDocument.insertString(publicChatDocument.getLength(),
                                              content + "\n", char_style);
            }
            catch (BadLocationException e) {
              e.printStackTrace();
            }
          }

          else if (_message.startsWith("LOGIN_PEOPLE:")) {

            String peopleName = _message.substring(_message.indexOf(":") + 1);
            peopleTable.put(peopleName, peopleName);
            model.addElement( (String) peopleTable.get(peopleName));
            peopleList.repaint();
          }

          else if (_message.startsWith("SEND_FILE:")) {
            System.out.println(_message.substring(_message.indexOf("SEND_FILE:")+10));
            String _requestPeople = _message.substring(_message.indexOf("SEND_FILE:")+10,_message.indexOf("#TOSENDFILE#"));
            String _toSendFile=_message.substring(_message.indexOf("#TOSENDFILE#")+12,_message.indexOf("#IPADDRESS#"));
            String _ipAddress=_message.substring(_message.indexOf("#IPADDRESS#")+11,_message.indexOf("#PORT#"));

            int port=(Integer.valueOf(_message.substring(_message.lastIndexOf("#PORT#")+6))).intValue();
            System.out.println(_requestPeople+"  "+_toSendFile);
            File file=new File(_toSendFile);
            try {
              privateChatDocument.insertString(privateChatDocument.getLength(),
                                               _requestPeople+"要向您发送文件"+file.getName() + "\n", char_style);
              fb=new FileDisposeButton(_requestPeople,_toSendFile,_ipAddress,port);
              jpanel4.add(fb);
              jpanel4.repaint();
              jpanel4.validate();
            }
            catch (BadLocationException e) {
              e.printStackTrace();
            }
          }


          else if (_message.startsWith("AGREE_ACCEPT:")) {

          }
          else if (_message.startsWith("DISAGREE_ACCEPT:")) {

          }
          else if (_message.startsWith("PEOPLE_LEAVE:")) {

          }
          Thread.sleep(5);
        //}

      }catch(Exception e){
        System.out.println("棘手文件错粗");
        e.printStackTrace();
      }
    }
  }
  public void stop(){
    try{
          this.socket.close();
          this.out.flush();
          this.out.close();
          this.in.close();
        }catch(Exception e1){
            e1.printStackTrace();
        }


  }






  public static void  main(String[] args){
    ChatArea chatarea=new ChatArea(new Hashtable());
    JFrame f=new JFrame();
    f.getContentPane().add(chatarea);
//    chatarea.setVisible(true);
    //f.setSize(800,700);
    f.setVisible(true);
    f.pack();

  }
  class Action implements ActionListener{
    public void actionPerformed(ActionEvent e){
      if(e.getSource()==sendMessageButton){
        try{
          String content=messageField.getText().trim();
          if(content.length()>0&&selectNameSB.length()>0){
            messageField.setText("");
            if (toPeople.contains("大家")) {
              publicChatDocument.insertString(publicChatDocument.getLength(),
                                   "您对大家说:" +content + "\n", char_style);
              out.writeUTF("PUBLIC_MESSAGE:" + "#MESSAGECONTENT#" + content);
            }
            else {
              Enumeration enum = toPeople.elements();
              while (enum.hasMoreElements()) {
                peoples = peoples + enum.nextElement() + "$";
              }
              privateChatDocument.insertString(privateChatDocument.getLength(),
                                               "您对" + selectNameSB + "说:" +
                                               content + "\n", char_style);
              out.writeUTF("PRIVATE_MESSAGE:" + "#MESSAGECONTENT#" + content +
                           "#TOPEOPLE#" + peoples);
            }
          }else{
            sendObject.setText("请选择对象");
          }
        }catch(BadLocationException bade){}
         catch(IOException e2){
          e2.printStackTrace();
        }
      }
      else if(e.getSource()==clearSendObjectButton){

        toPeople.removeAllElements();
        selectNameSB.delete(0,selectNameSB.length());
        sendObject.setText("");
      }
      else if(e.getSource()==sendFile){
        int state=chooser.showOpenDialog(null);
        file=chooser.getSelectedFile();
        if(file!=null&&state==(chooser.APPROVE_OPTION)){

         ClientSendFile clientSendFile=new ClientSendFile(file,toPeople);

        }
      }
      else if(e.getSource()==login){
       loginDialog.setVisible(true);
     }
     else if(e.getSource()==loginOut){
       if(socket!=null){
         try {
           socket.close();
           out.flush();
           out.close();
           in.close();
         }
         catch (IOException ioe) {}
       }
         System.exit(0);

     }
     /*else if(e.getSource()==agreeButton){

      }
      else if(e.getSource()==disagreeButton){

      }
      else if(e.getSource()==otherSaveButton){

      }*/

    }
  }

}








⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -