ChatRoom.java
上传用户:tendy5003
上传日期:2022-07-16
资源大小:210k
文件大小:15k
源码类别:

ICQ/即时通讯

开发平台:

Java

  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import java.net.*;
  5. import java.io.*;
  6. import java.util.*;
  7. /*<p>Title:HappyChat聊天系统聊天程序</p>
  8.  *<p>Description:系统用户登录后进行聊天</p>
  9.  *<p>Copyright:Copyright (C)2006</p>
  10.  *<p>Filename:ChatRoom.java</p>
  11.  *@author 刘志成
  12.  *@version 1.0
  13.  */
  14. public class ChatRoom extends Thread implements ActionListener
  15. {
  16. static JFrame frmChat;
  17. JPanel  pnlChat;
  18. JButton  btnCls,btnExit,btnSend,btnClear,btnSave,btnTimer,btnSendFile,btnBrowse;
  19. JLabel  lblUserList,lblUserMessage,lblSendMessage,lblChatUser;
  20. JLabel  lblUserTotal,lblCount,lblBack,lblFile;
  21. JTextField txtMessage,txtFile;
  22. java.awt.List  lstUserList;
  23. TextArea  taUserMessage;
  24. JComboBox  cmbUser;
  25. JCheckBox  chPrivateChat;
  26. String  strServerIp,strLoginName;
  27. Thread  thread;
  28. JMenuBar mbChat;
  29. JMenu mnuSystem,mnuHelp;
  30. JMenuItem mnuiCls,mnuiSave,mnuiClock,mnuiExit,mnuiContent,mnuiIndex,mnuiAbout;
  31.     //用于将窗口用于定位
  32. Dimension scrnsize;
  33. Toolkit toolkit=Toolkit.getDefaultToolkit();
  34. //构造方法
  35. public ChatRoom(String name,String ip)
  36. {
  37.     strServerIp=ip;
  38.     strLoginName=name;
  39.    frmChat=new JFrame("聊天室"+"[用户:"+name+"]");
  40.     pnlChat=new JPanel(); 
  41.     frmChat.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  42.     frmChat.getContentPane().add(pnlChat);
  43.         Font fntDisp1=new Font("宋体",Font.PLAIN,12);
  44.     //Font fntDisp2=new Font("宋体",Font.PLAIN,11);
  45.     
  46.     mbChat=new JMenuBar();
  47.     mnuSystem=new JMenu("系统(S)");
  48.     mnuSystem.setMnemonic(KeyEvent.VK_S);
  49.     mnuSystem.setFont(fntDisp1);
  50.     mnuHelp=new JMenu("帮助(H)");
  51.     mnuHelp.setMnemonic(KeyEvent.VK_H);
  52.     mnuHelp.setFont(fntDisp1);
  53. mbChat.add(mnuSystem);
  54. mbChat.add(mnuHelp);
  55. mnuiCls=new JMenuItem("清除屏幕显示");
  56. mnuiCls.setFont(fntDisp1);
  57. mnuiSave=new JMenuItem("保存聊天记录");
  58. mnuiSave.setFont(fntDisp1);
  59. mnuiClock=new JMenuItem("查看时间");
  60. mnuiClock.setFont(fntDisp1);
  61. mnuiExit=new JMenuItem("退出系统");
  62. mnuiExit.setFont(fntDisp1);
  63. mnuSystem.add(mnuiCls);
  64. mnuSystem.add(mnuiSave);
  65. mnuSystem.add(mnuiClock);
  66. mnuSystem.add(mnuiExit);
  67. mnuiContent=new JMenuItem("目录");
  68. mnuiContent.setFont(fntDisp1);
  69. mnuiIndex=new JMenuItem("索引");
  70. mnuiIndex.setFont(fntDisp1);
  71. mnuiAbout=new JMenuItem("关于[HappyChat聊天系统]...");
  72. mnuiAbout.setFont(fntDisp1);
  73. mnuHelp.add(mnuiContent);
  74. mnuHelp.add(mnuiIndex);
  75. mnuHelp.add(mnuiAbout);
  76. frmChat.setJMenuBar(mbChat);
  77.     
  78.     String list[]={"所有人"};  
  79.     btnCls=new JButton("清屏(C)");
  80.     btnExit=new JButton("退出(X)");
  81.     btnSend=new JButton("发送(N)");
  82.     btnSave=new JButton("保存(S)");
  83.     btnTimer=new JButton("时钟(T)");
  84.     btnSendFile=new JButton("发送文件(F)");
  85.     btnBrowse=new JButton("浏览...");
  86.     lblUserList=new JLabel("【在线用户列表】");
  87.     lblUserMessage=new JLabel("【聊天信息】");
  88.     lblSendMessage=new JLabel("聊天内容:");
  89.     lblChatUser=new JLabel("你对:"); 
  90.     lblUserTotal=new JLabel("在线人数:");
  91.     lblCount=new JLabel("0");
  92.     lblFile=new JLabel("附件:");
  93.     txtFile=new JTextField(20);
  94.     lstUserList=new java.awt.List();
  95.     txtMessage=new JTextField(170);
  96.     cmbUser         =new JComboBox(list);
  97.     chPrivateChat =new JCheckBox("私聊");
  98.     taUserMessage=new TextArea("",300,200,TextArea.SCROLLBARS_VERTICAL_ONLY);//只能向下滚动
  99.     taUserMessage.setEditable(false);   //不可写入
  100.     
  101.     /*  该布局采用手动布局           *
  102.  * setBounds设置组件位置        *
  103.  *  setFont设置字体、字型、字号  *
  104.  * setForeground设置文字的颜色  *
  105.  *  setBackground设置背景色      *
  106.  *  setOpaque将背景设置为透明    */
  107.         
  108.     pnlChat.setLayout(null);
  109. pnlChat.setBackground(new Color(52,130,203));
  110. btnSendFile.setBounds(250,360,100,25);
  111. btnBrowse.setBounds(170,360,80,25);
  112. btnTimer.setBounds(400,360,80,25);
  113. btnSave.setBounds(500,330,80,25);
  114.     btnCls.setBounds(400,330,80,25);
  115.     btnExit.setBounds(500,360,80,25);
  116.     btnSend.setBounds(500,300,80,25);
  117.     
  118.     lblFile.setBounds(10,330,40,25);
  119.     lblUserList.setBounds(5,0,120,40);
  120.         lblUserTotal.setBounds(130,0,60,40);
  121.     lblCount.setBounds(190,0,60,40);
  122.     lblUserMessage.setBounds(225,0,180,40);
  123.     lblChatUser.setBounds(10,290,40,40);
  124.     lblSendMessage.setBounds(210,290,60,40);
  125.     //lblUserTotal.setBounds(10,340,100,40);
  126.     //lblCount.setBounds(73,340,100,40);
  127.     txtFile.setBounds(50,330,300,25);
  128.     lstUserList.setBounds(5,40,210,255);
  129.     taUserMessage.setBounds(225,40,360,255);
  130.     txtMessage.setBounds(270,300,210,25);
  131.     cmbUser.setBounds(50,300,80,25);
  132.     chPrivateChat.setBounds(135,302,60,20);
  133.     
  134.     btnSendFile.setFont(fntDisp1);
  135.     btnBrowse.setFont(fntDisp1);
  136.     btnTimer.setFont(fntDisp1);
  137. btnCls.setFont(fntDisp1);
  138. btnExit.setFont(fntDisp1);
  139. btnSend.setFont(fntDisp1);
  140. btnSave.setFont(fntDisp1);
  141. lblFile.setFont(fntDisp1);
  142. lblUserList.setFont(fntDisp1);
  143. lblUserMessage.setFont(fntDisp1);
  144. lblChatUser.setFont(fntDisp1);
  145. lblSendMessage.setFont(fntDisp1);
  146. lblUserTotal.setFont(fntDisp1);
  147. lblCount.setFont(fntDisp1);
  148. txtFile.setFont(fntDisp1);
  149. cmbUser.setFont(fntDisp1);
  150. chPrivateChat.setFont(fntDisp1);
  151. taUserMessage.setFont(new Font("宋体",Font.PLAIN,12));
  152. lblUserList.setForeground(Color.YELLOW);
  153. lblUserMessage.setForeground(Color.YELLOW);
  154. lblSendMessage.setForeground(Color.black);
  155. lblChatUser.setForeground(Color.black);
  156. lblSendMessage.setForeground(Color.black);
  157. lblUserTotal.setForeground(Color.YELLOW);
  158. lblCount.setForeground(Color.YELLOW);
  159. cmbUser.setForeground(Color.black);
  160. chPrivateChat.setForeground(Color.black);
  161. lstUserList.setBackground(Color.white);
  162. taUserMessage.setBackground(Color.white);
  163. btnBrowse.setBackground(Color.PINK);
  164. btnSendFile.setBackground(Color.PINK);
  165. btnTimer.setBackground(Color.ORANGE);
  166. btnCls.setBackground(Color.ORANGE);
  167.     btnExit.setBackground(Color.ORANGE);
  168.     btnSend.setBackground(Color.PINK);
  169.     btnSave.setBackground(Color.ORANGE);
  170. pnlChat.add(lblFile);
  171. pnlChat.add(txtFile);
  172. pnlChat.add(btnSendFile);
  173. pnlChat.add(btnBrowse);
  174. pnlChat.add(btnTimer);
  175. pnlChat.add(btnCls);
  176.     pnlChat.add(btnExit);
  177.     pnlChat.add(btnSend);
  178.     pnlChat.add(btnSave);
  179.     pnlChat.add(lblUserList);
  180.     pnlChat.add(lblUserMessage);
  181.     pnlChat.add(lblSendMessage);
  182.     pnlChat.add(lblChatUser);
  183.     pnlChat.add(lblUserTotal);
  184.     pnlChat.add(lblCount);
  185.     pnlChat.add(lstUserList);
  186.     pnlChat.add(taUserMessage);
  187.     pnlChat.add(txtMessage);
  188.     pnlChat.add(cmbUser);
  189.     pnlChat.add(chPrivateChat);
  190.     
  191.     frmChat.addWindowListener(new Windowclose());
  192.     btnTimer.addActionListener(this);
  193.     btnCls.addActionListener(this);
  194.     btnExit.addActionListener(this);
  195.     btnSend.addActionListener(this);
  196.     btnSave.addActionListener(this);
  197.     lstUserList.addActionListener(this);
  198.     txtMessage.addActionListener(this);
  199.    
  200.     
  201.     //启动聊天页面信息刷新线程
  202. Thread thread = new Thread(this);
  203.        thread.start();
  204.     
  205. //     Icon log=new ImageIcon("images\chat.jpg");
  206. //   lblBack = new JLabel(log);
  207. // lblBack.setBounds(1, 1, 600,420);
  208. // pnlChat.add(lblBack);
  209.     frmChat.setSize(600,440);
  210.     frmChat.setVisible(true);
  211.     frmChat.setResizable(false);
  212.     
  213.     //将窗口定位在屏幕中央
  214.      scrnsize=toolkit.getScreenSize();
  215.      frmChat.setLocation(scrnsize.width/2-frmChat.getWidth()/2,
  216.                       scrnsize.height/2-frmChat.getHeight()/2);
  217.      Image img=toolkit.getImage("images\appico.jpg");
  218.         frmChat.setIconImage(img);
  219. }  //构造方法结束
  220. public void run()
  221. {   
  222.     int intMessageCounter=0;
  223.     int intUserTotal=0;
  224.     boolean isFirstLogin=true; //判断是否刚登陆
  225.     boolean isFound;      //判断是否找到用户
  226.     Vector user_exit=new Vector();
  227.     try
  228.     {
  229. for(;;)
  230. {
  231.           Socket toServer;
  232.   toServer=new Socket(strServerIp,1001);
  233. //将信息发往服务器
  234.       Message messobj=new Message();
  235.      ObjectOutputStream streamtoserver=new ObjectOutputStream(toServer.getOutputStream());
  236.     streamtoserver.writeObject((Message)messobj);
  237.    //收来自服务器的信息
  238.      ObjectInputStream streamfromserver=new ObjectInputStream(toServer.getInputStream());
  239.     messobj=(Message)streamfromserver.readObject();
  240.   ////////刷新聊天信息列表//////////
  241.   if (isFirstLogin)   //如果刚登陆
  242. {
  243.   intMessageCounter=messobj.chat.size();   //屏蔽该用户登陆前的聊天内容
  244.   isFirstLogin=false;
  245. }
  246. //  taUserMessage.setText("");
  247. for (int i=intMessageCounter;i<messobj.chat.size();i++)
  248. {
  249.     Chat temp=(Chat)messobj.chat.elementAt(i);
  250.      String temp_message;
  251.     if (temp.chatUser.equals(strLoginName))
  252.     {
  253.            if(temp.chatToUser.equals(strLoginName))
  254.           {
  255.             temp_message="系统提示您:请不要自言自语!"+"n";
  256.           }
  257.           else
  258.           {
  259.               if (!temp.whisper)   //不是悄悄话
  260.               {
  261.                  temp_message="【你】对【"+temp.chatToUser+"】说:"+temp.chatMessage+"n";
  262.               }
  263.               else
  264.               {
  265.                   temp_message="【你】悄悄对【"+temp.chatToUser+"】说:"+temp.chatMessage+"n";
  266.               }
  267.           }
  268.       }
  269.       else
  270.       {
  271.           if(temp.chatToUser.equals(strLoginName))
  272.           {
  273.               if (!temp.whisper)   //不是悄悄话
  274.               {
  275.                   temp_message="【"+temp.chatUser+"】对【你】说:"+temp.chatMessage+"n";
  276.               }
  277.               else
  278.               {
  279.                  temp_message="【"+temp.chatUser+"】悄悄对【你】说:"+temp.chatMessage+"n";
  280.               }
  281.           }
  282.           else
  283.           {
  284.               if (!temp.chatUser.equals(temp.chatToUser))  //对方没有自言自语
  285.               {
  286.                  if (!temp.whisper)   //不是悄悄话
  287.                  {
  288.                      temp_message="【"+temp.chatUser+"】对【"+temp.chatToUser+"】说:"+temp.chatMessage+"n";
  289.                   }
  290.                   else
  291.                   {
  292.                    temp_message="";
  293.                   }
  294.               }
  295.               else
  296.               {
  297.                  temp_message="";
  298.               }
  299.            }
  300.        }
  301.        taUserMessage.append(temp_message);
  302.        intMessageCounter++;
  303.     } 
  304.         
  305. ////////刷新在线用户//////////
  306. lstUserList.clear();
  307. for (int i=0;i<messobj.userOnLine.size();i++)
  308. {
  309.   String User=(String)messobj.userOnLine.elementAt(i);
  310. lstUserList.addItem(User);
  311.     }
  312.      Integer a=new Integer(messobj.userOnLine.size());
  313. lblCount.setText(a.toString());
  314. //显示用户进入聊天室的信息
  315. if(messobj.userOnLine.size()>intUserTotal)
  316. {
  317.      String tempstr=messobj.userOnLine.elementAt(messobj.userOnLine.size()-1).toString();
  318.      if(!tempstr.equals(strLoginName))
  319. {
  320. taUserMessage.append("【"+tempstr+"】来了"+"n");
  321. }
  322. }
  323.     //显示用户离开聊天室的信息
  324.     if(messobj.userOnLine.size()<intUserTotal)
  325.     {
  326.          for(int b=0;b<user_exit.size();b++)
  327.          {
  328.              isFound=false;
  329.              for(int c=0;c<messobj.userOnLine.size();c++)
  330.              {
  331.                  if(user_exit.elementAt(b).equals(messobj.userOnLine.elementAt(c)))
  332.                  {
  333. isFound=true;
  334.     break;
  335.     }
  336.          } 
  337.      if(!isFound)  //没有发现该用户
  338. {
  339.     if(!user_exit.elementAt(b).equals(strLoginName))
  340.      {
  341.          taUserMessage.append("【"+user_exit.elementAt(b)+"】走了"+"n");
  342.      }
  343. }
  344. }
  345. }
  346. user_exit=messobj.userOnLine;    
  347. intUserTotal=messobj.userOnLine.size();
  348.      streamtoserver.close();
  349.      streamfromserver.close();
  350.      toServer.close();
  351.      thread.sleep(1000);
  352. }
  353.     
  354. }
  355. catch (Exception e)
  356. {
  357. JOptionPane jop = new JOptionPane();
  358. jop.showMessageDialog(null,"不能连接服务器!");
  359. System.out.println(e);
  360. }
  361. }  //run()结束
  362. ///////////监听按钮响应//////////////
  363.     public void actionPerformed(ActionEvent ae)
  364.     {
  365.      Object source=(Object)ae.getSource();
  366.      if (source.equals(btnTimer))
  367.      {
  368.      new Clock();
  369.      }
  370.      if(source.equals(btnCls))
  371.      {
  372.          clearMessage();
  373.      }
  374.      if(source.equals(btnExit))
  375.      {
  376.          exit();
  377.      }
  378.      if(source.equals(btnSend))
  379.      {
  380.      sendMessage();
  381.      }
  382.      if(source.equals(btnSave))
  383.      {
  384.          saveMessage();
  385.      }
  386.      if(source.equals(lstUserList))  //双击列表框
  387.      {
  388.      changeUser();
  389.      }
  390.     } // actionPerformed()结束
  391.     
  392.     
  393.     ///////////监听窗口关闭响应//////////////
  394.     class Windowclose extends WindowAdapter
  395.     {
  396.         public void windowClosing(WindowEvent e)
  397.         {
  398.          exit();
  399.         }
  400.     }
  401.     
  402.     //"清屏"按钮
  403.     public void  clearMessage()
  404.     {
  405.         taUserMessage.setText("");
  406.     }
  407.     
  408.     //"退出"按钮
  409.     public void exit()
  410.     {
  411.         Exit exit=new Exit();
  412.         exit.exitname=strLoginName;
  413.         //发送退出信息
  414.         try
  415.         {
  416.             Socket toServer=new Socket(strServerIp,1001);
  417.             //向服务器发送信息
  418.             ObjectOutputStream outObj=new ObjectOutputStream(toServer.getOutputStream());
  419.             outObj.writeObject(exit);
  420.             outObj.close();
  421.      toServer.close();
  422.      frmChat.dispose();
  423.         }
  424.         catch(Exception e)
  425.         {
  426.         }
  427.     
  428.     }  //exit()结束
  429.     
  430.     //"发送"按钮
  431.     public void sendMessage()
  432.     {
  433.      Chat chatobj=new Chat();
  434.      chatobj.chatUser=strLoginName;
  435.      chatobj.chatMessage=txtMessage.getText();
  436.      chatobj.chatToUser=String.valueOf(cmbUser.getSelectedItem());
  437.      chatobj.whisper=chPrivateChat.isSelected()?true:false;
  438.         //向服务器发送信息
  439.      try
  440.      {
  441.      Socket toServer=new Socket(strServerIp,1001);
  442.      ObjectOutputStream outObj=new ObjectOutputStream(toServer.getOutputStream());
  443.      outObj.writeObject(chatobj);
  444.          txtMessage.setText("");   //清空文本框
  445.          outObj.close();
  446.      toServer.close();
  447.      }
  448.      catch(Exception e)
  449.      {
  450.      }
  451.     } //sendMessage()结束
  452.     
  453.     //"保存"按钮
  454.     public void saveMessage()
  455.     {
  456.      try
  457.      {
  458.      FileOutputStream  fileoutput=new FileOutputStream("message.txt",true);
  459.          String temp=taUserMessage.getText();
  460.          System.out.println(temp);
  461.          fileoutput.write(temp.getBytes());
  462.          fileoutput.close();
  463.         }
  464.         catch(Exception e)
  465.         {
  466.          System.out.println(e);
  467.         }
  468.         
  469.     }
  470.     
  471.     //将所选用户添加到cmbUser中
  472.    public void changeUser()
  473. {
  474. boolean key = true;
  475. String selected = lstUserList.getSelectedItem();
  476. for(int i = 0; i < cmbUser.getItemCount(); i++)
  477. {
  478.    if(selected.equals(cmbUser.getItemAt(i)))
  479.        {
  480.    key = false;
  481.        break;
  482.    }
  483. }
  484. if(key == true)
  485. {
  486.    cmbUser.insertItemAt(selected,0);
  487. }
  488. cmbUser.setSelectedItem(selected);
  489.     
  490.     } //changeUser()结束
  491.     
  492.     public static void main(String args[])
  493.     {
  494.      new ChatRoom("测试用户","127.0.0.1");
  495.     }
  496.     
  497. }