用JAVA打造自己的QQ(七)--源码篇客户端(主界面)

      主界面模仿了QQ的界面,通过树控件TREEVIEW可以自由地显示好友名单,在TREEVIEW上添加上下文菜单方便对好友的管理,如查看信息,删除好友,收发信息等,代码如下:

FMMAIN.JAVA:

package client;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import javax.swing.tree.*;
import javax.swing.border.*;
import java.util.Vector;
import java.net.*;
import java.io.*;
import com.borland.jbcl.layout.*;

public class fmMain extends JFrame implements Runnable,ActionListener,MouseListener{
  XYLayout xYLayout1 = new XYLayout();
  JTree jTree1=new JTree();
  JPopupMenu treePopupMenu;
  JPopupMenu systemPopupMenu;

  Icon icoMe=new ImageIcon(client.fmMain.class.getResource("pic/USER.gif"));
  Icon icoMenu=new ImageIcon(client.fmMain.class.getResource("pic/MenuButton_Normal.gif"));
  Icon icoMenuDown=new ImageIcon(client.fmMain.class.getResource("pic/MenuButton_Down.gif"));
  Icon icoMenuHover=new ImageIcon(client.fmMain.class.getResource("pic/MenuButton_Hover.gif"));
  Icon icoBackground=new ImageIcon(client.fmMain.class.getResource("pic/Background.gif"));
  Icon icoMsg=new ImageIcon(client.fmMain.class.getResource("pic/msg.gif"));
  Icon icoSearch=new ImageIcon(client.fmMain.class.getResource("pic/Search.gif"));
  JLabel jLabel1 = new JLabel(icoMe,SwingConstants.LEFT);

  JButton btnMenu = new JButton(icoMenu);
  JButton btnMsg = new JButton(icoMsg);
  JButton btnSearch = new JButton(icoSearch);

  //以下是网络相关变量
    Socket socket;
    BufferedReader in;
    PrintWriter out;
    DatagramPacket sendPacket,receivePacket;
    DatagramSocket sendSocket,receiveSocket;
    int receivePORT=7777;//
    int sendPort=7777;//单机调试请改动这里,谢谢!!!!!
    String server;
    int serverport;
    byte array[]=new byte[512];
    Thread thread;
    String received;
    boolean fromunknow=false;

    ///friendinfo
    //以下是好友基本信息变量,比如呢称,ip地址等
    public FriendsInfo friendsinfo=new FriendsInfo();
   //以下是临时变量保存临时的好友(加了我但我没加他的)
    public FriendsInfo  unknownsinfo=new FriendsInfo();
    public Vector myInfo;  //对应有8个字段的信息:姓名  JICQ  IP  在线状态  头像   email  info  comefrom sex
    int myjicq;
  public fmMain(Vector myinfo,String sername,int serport ){
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
       myInfo=myinfo;
       myjicq=Integer.parseInt(myinfo.get(1).toString());
       server=sername;
       serverport=serport;
       jbInit();
       ConnectServer(myjicq);//changed from:ConnectServer(myjicq);
       ReadFriendsAndUnknownsInfo(friendsinfo,unknownsinfo);
       initTree();
       CreatUDP();
       TellFriendsMyStatus("online");
       createPopupMenu();
      // findf=new FindFriend2(myjicq,server,serverport);//to change
      // findf.setBounds(200,150,300,300);
       thread=new Thread(this);
       thread.start();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }//end main*****

  void jbInit() throws Exception{
    xYLayout1.setWidth(175);
    xYLayout1.setHeight(412);
    this.getContentPane().setLayout(xYLayout1);
    this.getContentPane().setBackground(SystemColor.desktop);
    this.setForeground(SystemColor.desktop);
    this.setTitle("JICQ2005");
    this.addWindowListener(new fmMain_this_windowAdapter(this));
    jTree1.setBackground(SystemColor.inactiveCaptionText);
    jTree1.setAutoscrolls(true);
    jTree1.setBorder(BorderFactory.createLoweredBevelBorder());
    jTree1.setOpaque(true);
    jTree1.setScrollsOnExpand(true);
    jTree1.setShowsRootHandles(false);
    jLabel1.setForeground(SystemColor.window);
    jLabel1.setBorder(null);
    jLabel1.setIcon(icoMe);
    jLabel1.setText(myInfo.get(0).toString()+"(#"+myjicq+")");
    jLabel1.setIconTextGap(4);
    btnMenu.setBackground(SystemColor.desktop);
    btnMenu.setBorder(BorderFactory.createEtchedBorder());
    btnMenu.setHorizontalAlignment(SwingConstants.CENTER);
    btnMenu.setPressedIcon(icoMenuDown);
    btnMenu.setRolloverIcon(icoMenuHover);
    btnMsg.setBackground(SystemColor.desktop);
    btnMsg.setBorder(BorderFactory.createEtchedBorder());
    btnSearch.setBackground(SystemColor.desktop);
    btnSearch.setBorder(BorderFactory.createEtchedBorder());
    btnSearch.addActionListener(new fmMain_btnSearch_actionAdapter(this));

    this.getContentPane().add(jLabel1,        new XYConstraints(5, 1, 164, 46));
    this.getContentPane().add(btnMenu,    new XYConstraints(4, 379, 65, 24));
    this.getContentPane().add(btnMsg,          new XYConstraints(72, 379, 29, 24));
    this.getContentPane().add(btnSearch,       new XYConstraints(106, 379, 24, 24));
  }

  //以下该函数连接服务器
  public void  ConnectServer(int myid){
   try{
       socket=new Socket(InetAddress.getByName(server),serverport);
       in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
       out=new PrintWriter(new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream())),true);

     }catch(IOException e1){System.out.println("false");}
//以下在列表中显示好友
     /*
     DefaultListModel mm=(DefaultListModel)list.getModel();
     int  picid;
     for(int p=0;p<friendnames.size();p++){
       picid=Integer.parseInt(picno.get(p).toString());
       if(status.get(p).equals("1")){
            mm.addElement(new Object[]{friendnames.get(p),new ImageIcon(picsonline[picid])});}
       else {
          mm.addElement(new Object[]{friendnames.get(p),new ImageIcon(picsoffline[picid])});
        }
     }//for
      */
  }  //connectto server

void initTree(){
    treeRefresh();
}
 void treeRefresh()
 {
    //以下在树中显示好友
   DefaultMutableTreeNode root=new DefaultMutableTreeNode("Jicq2005");
   DefaultMutableTreeNode friends=new DefaultMutableTreeNode("我的好友("+friendsinfo.getOnlineCount()+
                                                             "/"+friendsinfo.friTotal+")");
   DefaultMutableTreeNode unknowns=new DefaultMutableTreeNode("陌生人("+unknownsinfo.getOnlineCount()+
                                                              "/"+unknownsinfo.friTotal+")");
   for(int i=0;i<friendsinfo.friTotal;i++)
   {
     System.out.println(friendsinfo.friNames.get(i).toString());
     if(Integer.parseInt(friendsinfo.friStatus.get(i).toString().trim()) ==1)
        friends.add(new DefaultMutableTreeNode(friendsinfo.friNames.get(i)+"(在线)",false));
     else
        friends.add(new DefaultMutableTreeNode(friendsinfo.friNames.get(i)+"(离线)",false));
   }
   for(int i=0;i<unknownsinfo.friTotal;i++)
   {
     System.out.println(unknownsinfo.friNames.get(i).toString());
     if(Integer.parseInt(unknownsinfo.friStatus.get(i).toString().trim()) ==1)
        unknowns.add(new DefaultMutableTreeNode(unknownsinfo.friNames.get(i)+"(在线)",false));
     else
        unknowns.add(new DefaultMutableTreeNode(unknownsinfo.friNames.get(i)+"(离线)",false));
   }

   //System.out.println("come here,read friends info successfully");
   root.add(friends);
   root.add(unknowns);
   this.jTree1.setVisible(false);
   this.jTree1=null;
   jTree1=new JTree(root);
   jTree1.updateUI();
   jTree1.setBackground(SystemColor.inactiveCaptionText);
   jTree1.setAutoscrolls(true);
   jTree1.setBorder(BorderFactory.createLoweredBevelBorder());
   jTree1.setOpaque(true);
   jTree1.setScrollsOnExpand(true);
   jTree1.setShowsRootHandles(false);
   jTree1.setRootVisible(false);
   jTree1.setForeground(SystemColor.desktop);

    MouseListener ml = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                 int selRow = jTree1.getRowForLocation(e.getX(), e.getY());
                 TreePath selPath = jTree1.getPathForLocation(e.getX(), e.getY());
                 if(selRow != -1) {
                   if(e.getClickCount() == 2) {
                       DefaultMutableTreeNode friNode=(DefaultMutableTreeNode)selPath.getLastPathComponent();
                       if(friNode.isLeaf()){
                         DefaultMutableTreeNode parent = (DefaultMutableTreeNode)friNode.getParent();
                         if (!parent.isRoot()) {
                           int index = parent.getIndex(friNode);
                           DefaultMutableTreeNode root = (DefaultMutableTreeNode)parent.getParent();
                           System.out.println(root);
                           int index2 = root.getIndex(parent);
                           myDoubleClick(index, index2);
                         }
                       }
                     }//end else
                 }
             }
             void myDoubleClick(int INDEX,int INDEX2){
               //System.out.println("double click event occured");
               fmSend Send;
               if (INDEX2==1)
                     Send=new fmSend(INDEX,unknownsinfo,sendSocket,myInfo);
               else
                     Send=new fmSend(INDEX,friendsinfo,sendSocket,myInfo);
               Send.show();
            }
  };

   jTree1.addMouseListener(ml);
   jTree1.addMouseListener(this);
   this.repaint();
   jTree1.repaint();
   jTree1.setVisible(true);
   this.getContentPane().add(jTree1,                new XYConstraints(5, 51, 164, 319));
   this.getContentPane().repaint();
 }


void TellFriendsMyStatus(String status) {
 try{
       String whoips;
       String  s=status+myjicq;
       System.out.println(s);
       byte[] data=s.getBytes();
       //以下为通知在线的陌生人
       for(int i=0;i<unknownsinfo.friTotal;i++){
         if(Integer.parseInt(unknownsinfo.getFriInfoAt(i).get(3).toString())==1)
           { whoips=unknownsinfo.getFriInfoAt(i).get(2).toString().trim();
             sendPacket = new
             DatagramPacket(data, s.length(), InetAddress.getByName(whoips),sendPort);
             sendSocket.send(sendPacket);
           }
       }//for
       //以下为通知在线的好友
       for(int i=0;i<friendsinfo.friTotal;i++){
         if(Integer.parseInt(friendsinfo.getFriInfoAt(i).get(3).toString())==1)
           { whoips=friendsinfo.getFriInfoAt(i).get(2).toString().trim();
             sendPacket = new
             DatagramPacket(data, s.length(), InetAddress.getByName(whoips),sendPort);
             sendSocket.send(sendPacket);
           }
       }//for
   } catch(IOException e2){
      e2.printStackTrace();System.exit(1);
  }
}/end tellfrienonline


private void ReadFriendsAndUnknownsInfo(FriendsInfo friends,FriendsInfo unknowns)
 {
   try
   {   friends.Reset();
       unknowns.Reset();
       out.println("readinfo");
       out.println(myjicq);
       //friends.friTotal=Integer.parseInt(in.readLine());
       //System.out.println("received friendsno:"+friends.friTotal);
       String friendname=" ";
       String friendjicqno,friendip,friendstatus,picinfo,email,infos,chatmsg,place,sex;
        do{
            friendname=in.readLine();
            if(friendname.equals("friendover"))  break;
            if(friendname.equals("false")){
               JOptionPane.showMessageDialog(this,
                    "JICQ系统提示:服务器读取好友信息错误,请重试!",
                    "JICQ2005提醒您",JOptionPane.INFORMATION_MESSAGE);
               friends.Reset();
               return;
            }
            friends.friNames.add(friendname);
            friendjicqno=in.readLine();
            friends.friJicqs.add(friendjicqno);
            friendip=in.readLine();
            friends.friIPs.add(friendip);
            friendstatus=in.readLine();
            friends.friStatus.add(friendstatus);
            //System.out.println("read friends'status info:"+friendstatus);
            picinfo=in.readLine();
            friends.friPics.add(picinfo);
            email=in.readLine();
            friends.friEmails.add(email);
            infos=in.readLine();
            friends.friInfos.add(infos);
            chatmsg=in.readLine();
            friends.chatInfo.add(chatmsg);
            place=in.readLine();
            friends.friPlaces.add(place);
            sex=in.readLine();
            friends.friSexes.add(sex);
          }while(!friendname.equals("friendover"));
           friends.friTotal=friends.friNames.size();
        //unknowns.friTotal=Integer.parseInt(String.valueOf(in.readLine()));
        //System.out.println("received unknowns:"+unknowns.friTotal);
        do{
            friendname=in.readLine();
            if(friendname.equals("unknownsover"))  break;
            if(friendname.equals("false")){
               JOptionPane.showMessageDialog(this,
                    "JICQ系统提示:服务器读取陌生人信息错误,请重试!",
                    "JICQ2005提醒您",JOptionPane.INFORMATION_MESSAGE);
               unknowns.Reset();
               return;
            }
            unknowns.friNames.add(friendname);
            friendjicqno=in.readLine();
            System.out.println("friNo:"+friendjicqno);
            unknowns.friJicqs.add(new Integer(friendjicqno));
            friendip=in.readLine();
            System.out.println("friIp:"+friendip);
            unknowns.friIPs.add(friendip);
            friendstatus=in.readLine();
            System.out.println("friStatus:"+friendstatus);
            unknowns.friStatus.add(friendstatus);
            //System.out.println("read friends'status info:"+friendstatus);
            picinfo=in.readLine();
            unknowns.friPics.add(picinfo);
            email=in.readLine();
            unknowns.friEmails.add(email);
            infos=in.readLine();
            unknowns.friInfos.add(infos);
            chatmsg=in.readLine();
            unknowns.chatInfo.add(chatmsg);
            place=in.readLine();
            unknowns.friPlaces.add(place);
            sex=in.readLine();
            unknowns.friSexes.add(sex);
            System.out.println("friSex:"+sex);
            System.out.println("sended one");
          }while(!friendname.equals("unknownsover"));
           unknowns.friTotal=unknowns.friNames.size();
    }catch(IOException e2){
        JOptionPane.showMessageDialog(this,
                    "JICQ系统提示:读取服务器信息错误,请重试!",
                    "JICQ2005提醒您",JOptionPane.INFORMATION_MESSAGE);
     }
 }

 public void CreatUDP(){
    try{ sendSocket=new DatagramSocket();
         receiveSocket=new DatagramSocket(receivePORT);
         System.out.println("creat udp ok");
    }catch(SocketException se){se.printStackTrace();System.out.println("false udp");}
  }// creat udp end

  public void createPopupMenu() {
        JMenuItem menuItem;
        //Create the treePopupMenu****************************************
        treePopupMenu = new JPopupMenu();
        menuItem = new JMenuItem(" ☆ 收发讯息");
        menuItem.addActionListener(this);
        treePopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆ 查看资料");
        menuItem.addActionListener(this);
        treePopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆ 删除好友");
        menuItem.addActionListener(this);
        treePopupMenu.add(menuItem);
        menuItem = new JMenuItem("----------------");
        menuItem.addActionListener(this);
        treePopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆ 传送文件");
        menuItem.addActionListener(this);
        treePopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆ 刷新列表");
        menuItem.addActionListener(this);
        treePopupMenu.add(menuItem);


        //以下构造系统菜单***************************************************
        systemPopupMenu = new JPopupMenu();
        menuItem = new JMenuItem(" ☆☆ 个人设置");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆☆ 更改用户");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆☆ 注册向导");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆☆ 系统设置");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        menuItem = new JMenuItem("--------------------");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        menuItem = new JMenuItem("");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆☆  关    于");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        menuItem = new JMenuItem(" ☆☆  退    出");
        menuItem.addActionListener(this);
        systemPopupMenu.add(menuItem);
        //Add listener to the text area so the popup menu can come up.
        MouseListener systempopupListener = new PopupListener(systemPopupMenu);
        this.btnMenu.addMouseListener(systempopupListener);

    }

  void DeleteFriend(int delno){
      System.out.println("好友:"+delno+"将被删除!");
      out.println("delfriend");
      out.println(delno);//the friendjicq to del
      out.println(myjicq);//my jicqno
      System.out.println("好友:"+delno+"被删除!");
   }//delfriend

//实现ActionListener的函数actionPerformed
  public void actionPerformed(ActionEvent e) {
         JMenuItem source = (JMenuItem)(e.getSource());
         //以下处理树的右键菜单
         if (source.getText()==" ☆ 收发讯息"){
           System.out.println("收发讯息处理");
            int[] selRows = jTree1.getSelectionRows();
            int selRow=selRows[selRows.length-1];
            TreePath selPath = jTree1.getSelectionPath();
            if(selRow != -1) {
                  DefaultMutableTreeNode friNode=(DefaultMutableTreeNode)selPath.getLastPathComponent();
                  if(friNode.isLeaf()){
                     DefaultMutableTreeNode parent = (DefaultMutableTreeNode)friNode.getParent();
                     if (!parent.isRoot()) {
                       int index = parent.getIndex(friNode);
                       DefaultMutableTreeNode root = (DefaultMutableTreeNode)parent.getParent();
                       //System.out.println(root);
                       int index2 = root.getIndex(parent);
                       fmSend Send;
                       if (index2==1)
                          Send=new fmSend(index,unknownsinfo,sendSocket,myInfo);
                       else
                          Send=new fmSend(index,friendsinfo,sendSocket,myInfo);
                       Send.pack();
                   }
               }
            }
          }

          if (source.getText()==" ☆ 查看资料"){
             int[] selRows = jTree1.getSelectionRows();
             int selRow=selRows[selRows.length-1];
             TreePath selPath = jTree1.getSelectionPath();
             if(selRow != -1) {
                   DefaultMutableTreeNode friNode=(DefaultMutableTreeNode)selPath.getLastPathComponent();
                   if(friNode.isLeaf()){
                      DefaultMutableTreeNode parent = (DefaultMutableTreeNode)friNode.getParent();
                      if (!parent.isRoot()) {
                        int index = parent.getIndex(friNode);
                        DefaultMutableTreeNode root = (DefaultMutableTreeNode) parent.
                            getParent();
                        int index2 = root.getIndex(parent);
                        if (index2 == 1) {
                          Vector temp = new Vector();
                          temp.add(unknownsinfo.friNames.get(index));
                          temp.add(unknownsinfo.friJicqs.get(index));
                          temp.add(unknownsinfo.friIPs.get(index));
                          temp.add(unknownsinfo.friStatus.get(index));
                          temp.add(unknownsinfo.friPics.get(index));
                          temp.add(unknownsinfo.friEmails.get(index));
                          temp.add(unknownsinfo.friInfos.get(index));
                          temp.add(unknownsinfo.friPlaces.get(index));
                          temp.add(unknownsinfo.friSexes.get(index));
                          fmShowInfo lookinfo = new fmShowInfo(temp);
                          lookinfo.show();
                        }
                        else{
                          Vector temp = new Vector();
                          temp.add(friendsinfo.friNames.get(index));
                          temp.add(friendsinfo.friJicqs.get(index));
                          temp.add(friendsinfo.friIPs.get(index));
                          temp.add(friendsinfo.friStatus.get(index));
                          temp.add(friendsinfo.friPics.get(index));
                          temp.add(friendsinfo.friEmails.get(index));
                          temp.add(friendsinfo.friInfos.get(index));
                          temp.add(friendsinfo.friPlaces.get(index));
                          temp.add(friendsinfo.friSexes.get(index));
                          fmShowInfo lookinfo = new fmShowInfo(temp);
                          lookinfo.show();
                        }
                      }
                   }
                 }
          }
          if (source.getText()==" ☆ 删除好友"){
            int[] selRows = jTree1.getSelectionRows();
            int selRow=selRows[selRows.length-1];
            TreePath selPath = jTree1.getSelectionPath();
            if(selRow != -1) {
                 DefaultMutableTreeNode friNode=(DefaultMutableTreeNode)selPath.getLastPathComponent();
                 if(friNode.isLeaf()){
                    DefaultMutableTreeNode parent = (DefaultMutableTreeNode)friNode.getParent();
                    if (!parent.isRoot()) {
                      int index = parent.getIndex(friNode);
                      DefaultMutableTreeNode root = (DefaultMutableTreeNode) parent.
                          getParent();
                      int index2 = root.getIndex(parent);
                      if(index2==1){
                        DeleteFriend(Integer.parseInt(unknownsinfo.friJicqs.get(index).toString()));
                        unknownsinfo.removeInfoAt(index);
                        treeRefresh();
                      }
                      else{
                        DeleteFriend(Integer.parseInt(friendsinfo.friJicqs.get(index).toString()));
                        friendsinfo.removeInfoAt(index);
                        treeRefresh();
                      }
                    }
                 }
          }}
        if (source.getText()==" ☆ 传送文件"){
           JOptionPane.showMessageDialog(this,"对不起,此功能暂未实现!","JICQ系统提示",JOptionPane.INFORMATION_MESSAGE);
         }
         if (source.getText()==" ☆ 刷新列表"){
           treeRefresh();
         }


          //以下处理系统菜单
         if (source.getText()==" ☆☆  退    出"){
           TellFriendsMyStatus("offline");
           out.println("logout");
           out.println(myjicq);
           System.exit(0);
         }
         if (source.getText()==" ☆☆ 个人设置"){
            fmUserConfig user=new fmUserConfig(myInfo);
            user.show();
          }
          if (source.getText()==" ☆☆ 注册向导"){
            String server=this.socket.getInetAddress().getHostAddress();
            System.out.println("the remote server:"+server);
            try{
              this.dispose();
              TellFriendsMyStatus("offline");
              out.println("logout");
              out.println(myjicq);
              this.socket.close();
              fmRegister d = new fmRegister(server, 10000); //打开新建窗口
              d.pack();
              d.setLocationRelativeTo(this);
              d.show();
            }catch(IOException e2){
               JOptionPane.showMessageDialog(this,"网络故障,请重试!","JICQ系统提示",JOptionPane.INFORMATION_MESSAGE);
            }
          }

          if (source.getText()==" ☆☆ 系统设置"){
            JOptionPane.showMessageDialog(this,"对不起,此功能暂未实现!","JICQ系统提示",JOptionPane.INFORMATION_MESSAGE);
          }
          if (source.getText()==" ☆☆  帮    助"){
               JOptionPane.showMessageDialog(this,"对不起,此功能暂未实现!","JICQ系统提示",JOptionPane.INFORMATION_MESSAGE);
          }
          if (source.getText()==" ☆☆  关    于"){
               fmAbout about =new fmAbout();
               about.show();
          }
          if (source.getText()==" ☆☆ 更改用户"){
            this.dispose();
            TellFriendsMyStatus("offline");
            out.println("logout");
            out.println(myjicq);

            fmLogin changeUser=new fmLogin();

            changeUser.pack();
         //Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = changeUser.getSize();
            if (frameSize.height > screenSize.height) {
                 frameSize.height = screenSize.height;
            }
            if (frameSize.width > screenSize.width) {
                 frameSize.width = screenSize.width;
            }
             changeUser.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
             changeUser.setVisible(true);
           }
    }

//实现MouseListener的几个函数
  public void mouseClicked(MouseEvent e){
  }
  public void mouseEntered(MouseEvent e){

  }
  public void mouseExited(MouseEvent e){
  }
  public void mousePressed(MouseEvent e){
  }
  public void mouseReleased(MouseEvent e){
    if(e.isPopupTrigger()){
        treePopupMenu.show(this.jTree1,e.getX(),e.getY());
    }
  }

  //以下函数无限监听好友的消息
    public  void  run(){
         while(true)
          {
           try{ for(int x=0;x<512;x++)array[x]=' ';
                 //创建数据报
                 //System.out.println("the main form Thread is running!");
                 receivePacket=new DatagramPacket(array,array.length);
                 receiveSocket.receive(receivePacket);
                 byte[] data=receivePacket.getData();
                 String infofromip=receivePacket.getAddress().getHostAddress().toString().trim();
                 int index=0;
                 received=new String(data,0,data.length);
                 String msg=received.trim();
                 System.out.println("the origin string length:"+received.length());
                 System.out.println("the changed string length:"+msg.length());
                 String tempstr;
                 int tx;
                 //friend online
                 if(received.substring(0,6).equals("online")){//有好友上线就变彩色

                   tempstr=received.substring(6).trim();
                     // System.out.println("str"+tempstr);
                     int tempgetjicq=Integer.parseInt(tempstr);
                      // System.out.println("id"+tempgetjicq);
                      while(index<friendsinfo.friTotal && friendsinfo.friTotal>0)
                     {
                       tx= Integer.parseInt(friendsinfo.friJicqs.get(index).toString());
                    //System.out.println("tx"+tx);
                       if(tempgetjicq==tx)break;
                       index++;
                     }
                     if (index<friendsinfo.friTotal){
                       friendsinfo.friIPs.setElementAt(infofromip,index);
                       friendsinfo.friStatus.setElementAt("1",index);
                       fmInform inform=new fmInform(true,"您的好友"+friendsinfo.getFriInfoAt(index).get(0).toString() + "上线了!",friendsinfo,0,sendSocket,myInfo);
                       inform.show();
                       treeRefresh();
                     }else
                     {
                       while (index < friendsinfo.friTotal + unknownsinfo.friTotal && unknownsinfo.friTotal>0)
                       {
                         tx = Integer.parseInt(unknownsinfo.friJicqs.get(index -
                             friendsinfo.friTotal).toString());
                         //System.out.println("tx"+tx);
                         if (tempgetjicq == tx)break;
                         index++;
                       }

                       if (index < friendsinfo.friTotal + unknownsinfo.friTotal) {
                            unknownsinfo.friIPs.setElementAt(infofromip,index-friendsinfo.friTotal);
                            unknownsinfo.friStatus.setElementAt("1",index-friendsinfo.friTotal);
                            fmInform inform=new fmInform(true,"陌生人'"+unknownsinfo.getFriInfoAt(index-friendsinfo.friTotal).get(0).toString() + "'上线了!",unknownsinfo,0,sendSocket,myInfo);
                            inform.show();
                            treeRefresh();
                       } //end if
                     }//end else
                   treeRefresh();
                 }//end online
      //friend offline
                 else  if(received.substring(0,7).equals("offline")){//如果有好友下线就变灰色
                      tempstr=received.substring(7).trim();
                      System.out.println("str"+tempstr);
                      int tempgetjicq=Integer.parseInt(tempstr);
                      System.out.println("id"+tempgetjicq);
                     while(index<friendsinfo.friTotal && friendsinfo.friTotal>0)
                     {  tx= Integer.parseInt(friendsinfo.friJicqs.get(index).toString());
                           //System.out.println("tx"+tx);
                           if(tempgetjicq==tx)break;
                           index++;
                      }
                      if(index<friendsinfo.friTotal){
                        infofromip="";
                        friendsinfo.friIPs.setElementAt(infofromip,index);
                        friendsinfo.friStatus.setElementAt("0",index);
                        fmInform inform=new fmInform(true,"好友'"+
                        friendsinfo.friNames.get(index).toString()+"'下线了!",friendsinfo,0,sendSocket,myInfo);
                        inform.show();
                         treeRefresh();
                       }
                      else{
                        while(index<friendsinfo.friTotal+unknownsinfo.friTotal && unknownsinfo.friTotal>0)
                        {  tx= Integer.parseInt(unknownsinfo.friJicqs.get(index-friendsinfo.friTotal).toString());
                         //System.out.println("tx"+tx);
                         if(tempgetjicq==tx)break;
                         index++;
                        }
                        if(index<friendsinfo.friTotal+unknownsinfo.friTotal){

                          infofromip="";
                           unknownsinfo.friIPs.setElementAt(infofromip,index-friendsinfo.friTotal);
                           unknownsinfo.friStatus.setElementAt("0",index-friendsinfo.friTotal);
                           fmInform inform=new fmInform(true,"陌生人'"+
                          unknownsinfo.friNames.get(index-friendsinfo.friTotal).toString()+"'下线了!",unknownsinfo,0,sendSocket,myInfo);
                          inform.show();
                           treeRefresh();
                         }
                      }
                   }//end friend offline

                    //someone add me as friend
                   else if(received.substring(0,9).equals("oneaddyou")){
                    //如果有人加我为好有,选择加还是不
                      tempstr=received.substring(9).trim();
                      System.out.println("str"+tempstr);
                      int tempgetjicq=Integer.parseInt(tempstr);
                      System.out.println("id"+tempgetjicq);

                      //tochange:to add
                      fmInform inform=new fmInform(true,"用户'"+
                          tempgetjicq+"把你加为好友名单!",unknownsinfo,0,sendSocket,myInfo);
                          inform.show();


               } //endsomeone add me as friend
               else{//否则就显示收到消息
                   int index4=0;
                   //  String infofromip=receivePacket.getAddress().getHostAddress().toString().trim();
                   while(index4<friendsinfo.friTotal && friendsinfo.friTotal>0)
                   {
                       String friendip=friendsinfo.friIPs.get(index4).toString().trim();
                       if (infofromip.equals(friendip)){                                   //problem:compare string
                          String nameinfo=friendsinfo.friNames.get(index4).toString().trim();

                          fromunknow=false;
                          friendsinfo.chatInfo.setElementAt(friendsinfo.chatInfo.get(index4).toString()+"/n["+nameinfo+"]  "+msg,index4);
                          fmInform inform=new fmInform(false,"好友 '"+nameinfo+"'发来消息",friendsinfo,index4,sendSocket,myInfo);
                          inform.show();

                          break;
                        }//if
                        index4++;
                   }//while

                   if(index4>=friendsinfo.friTotal){
                     while (index4 < friendsinfo.friTotal + unknownsinfo.friTotal && unknownsinfo.friTotal>0)
                     {
                       String friendip = unknownsinfo.friIPs.get(index4 -
                                 friendsinfo.friTotal).toString().trim();
                       fromunknow = true; //收到陌生人的消息

                       if (infofromip.equals(friendip)) {
                             String nameinfo = unknownsinfo.friNames.get(index4 -
                             friendsinfo.friTotal).toString().trim();

                             unknownsinfo.chatInfo.setElementAt(unknownsinfo.chatInfo.get(index4-friendsinfo.friTotal).toString()+"/n["+nameinfo+"] "+msg,index4-friendsinfo.friTotal);
                             fmInform inform=new fmInform(false,"陌生人'"+nameinfo+"'发来消息",unknownsinfo,index4-friendsinfo.friTotal,sendSocket,myInfo);
                             inform.show();
                              break;
                       }//end if
                       index4++;
                     } //while
                   }//end if
                    System.out.println(index4);
           }//end else
      }catch(IOException  ex){ex.printStackTrace();}
   }//end while
  }

  void this_windowClosing(WindowEvent e) {//关闭窗口时处理
    TellFriendsMyStatus("offline");
    out.println("logout");
    out.println(myjicq);
    System.exit(0);
  }

  void btnSearch_actionPerformed(ActionEvent e) {
       fmFind find=new fmFind(socket,in,out,myInfo,friendsinfo);
       find.show();
  }
}
  class PopupListener extends MouseAdapter {
          JPopupMenu popup;

          PopupListener(JPopupMenu popupMenu) {
              popup = popupMenu;
          }

          public void mousePressed(MouseEvent e) {
              maybeShowPopup(e);
          }

          public void mouseReleased(MouseEvent e) {
              maybeShowPopup(e);
          }

          private void maybeShowPopup(MouseEvent e) {
             // if (e.isPopupTrigger()) {
             popup.setBackground(SystemColor.desktop);
             popup.setForeground(SystemColor.inactiveCaption);
             popup.setFont(new Font("隶书",Font.PLAIN,16));
             popup.repaint();
             popup.updateUI();
             popup.show(e.getComponent(),
                             e.getX(), e.getY());
            //  }
          }

      }

class fmMain_this_windowAdapter extends java.awt.event.WindowAdapter {
  fmMain adaptee;

  fmMain_this_windowAdapter(fmMain adaptee) {
    this.adaptee = adaptee;
  }
  public void windowClosing(WindowEvent e) {
    adaptee.this_windowClosing(e);
  }
}

class fmMain_btnSearch_actionAdapter implements java.awt.event.ActionListener {
  fmMain adaptee;

  fmMain_btnSearch_actionAdapter(fmMain adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.btnSearch_actionPerformed(e);
  }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值