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

📄 chatapplet.java

📁 用java编写的一个聊天工具(有源代码)
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

public class chatApplet extends Applet 
                        implements ActionListener,
                                   KeyListener,
                                   ItemListener
{ /*以下用于定义UI变量*/
  Panel panel1=new Panel();        //用于放置输入姓名和连接两个按钮
  BorderLayout borderLayout1 = new BorderLayout();
  Panel panel2=new Panel();        //用于放置聊天信息显示
  Panel panel3=new Panel();        //用于放置发送信息区域
  Panel panel4=new Panel();        //用于放置聊天人员列表
  Panel panel5=new Panel();         //用于放置字体设置选项
  Panel panel6=new Panel();        //用于放置字体颜色
  FlowLayout flowLayout1=new FlowLayout();
  FlowLayout flowLayout2=new FlowLayout();
  Label label1=new Label();
  Label label2=new Label();
  TextField name_txt=new TextField(15);
  //------------------------------------
  Button button1=new Button();
  Button button2=new Button();
  Button button3=new Button();
  Button button4=new Button();  //chat record
  //------------------------------------
  TextArea current=new TextArea("",2,20,TextArea.SCROLLBARS_NONE);
  TextArea chat_txt=new TextArea("",20,20,TextArea.SCROLLBARS_VERTICAL_ONLY);
  TextArea msg_txt=new TextArea("",8,20,TextArea.SCROLLBARS_VERTICAL_ONLY);
  java.awt.List list1=new java.awt.List(13);
  //------------------------------------
  Checkbox ch1=new Checkbox("粗体");
  Checkbox ch2=new Checkbox("斜体");
  Checkbox ch3=new Checkbox("普通");
  CheckboxGroup gp=new CheckboxGroup();
  Checkbox cr1=new Checkbox("红色",gp,false);
  Checkbox cr2=new Checkbox("蓝色",gp,false);
  Checkbox cr3=new Checkbox("绿色",gp,false);
  Checkbox cr4=new Checkbox("黑色",gp,true);
  //------------------------------------
  Label label3=new Label("大小");
  TextField fontsize=new TextField("12");
  
  /*以下定义数据流和网络变量*/
  Socket soc=null;                   //定义连接套接字
  PrintStream ps=null;                 //定义打印流 
  Listen listen=null;                 //定义一个客户端线程
   
  /*以下定义普通成员变量*/
  boolean ctrldown;     //false-ctrl isn't be pressed
  boolean enterdown;    //false-enter isn't be pressed
  String color=null;
  String select=null;                 //被选中的用户
  int selecti=-1;
  
  public void init() throws HeadlessException                //初始化图形界面
  { resize(550,500);  
    this.setLayout(borderLayout1);
    label1.setText("姓名:");
    button1.setLabel("连接");
    button2.setLabel("退出");
    
    chat_txt.setEditable(false);
    current.setEditable(false);
    //set color
    panel1.setBackground(Color.pink);
    panel2.setBackground(Color.pink);
    panel3.setBackground(Color.pink);
    panel4.setBackground(Color.pink);
    panel5.setBackground(Color.pink);
    panel6.setBackground(Color.pink);
    chat_txt.setBackground(Color.lightGray);
    current.setBackground(Color.white);
    chat_txt.setVisible(true);
    current.setVisible(true);
    //set layout
    this.add(panel1,BorderLayout.NORTH);
    this.add(panel2,BorderLayout.CENTER);
    this.add(panel3,BorderLayout.SOUTH);
    this.add(panel4,BorderLayout.EAST);
    //panel1   
    panel1.add(label1,null);
    panel1.add(name_txt,null);
    panel1.add(button1,null);
    panel1.add(button2,null);
    //panel2
    panel2.setLayout(new BorderLayout());
    panel2.add(current,BorderLayout.NORTH);
    panel2.add(chat_txt,BorderLayout.CENTER);
    //panel4    
    panel4.setLayout(new BorderLayout());
    panel4.add(list1,BorderLayout.CENTER);
    panel4.add((new Label("在线人员")),BorderLayout.NORTH);
    panel4.add((new Label()),BorderLayout.EAST);
    //panel5
    panel5.setLayout(new FlowLayout());
    panel5.add(label3,null);
    panel5.add(fontsize,null);
    panel5.add(ch1,null);
    panel5.add(ch2,null);
    panel5.add(ch3,null);
    //panel6
    panel6.setLayout(new BorderLayout());
    panel6.add(cr1,BorderLayout.NORTH);
    panel6.add(cr2,BorderLayout.SOUTH);
    panel6.add(cr3,BorderLayout.CENTER);
    panel6.add(cr4,BorderLayout.EAST);
    //panel3
    panel3.setLayout(new BorderLayout());
    panel3.add(label2,BorderLayout.NORTH);
    panel3.add(msg_txt,BorderLayout.CENTER);
    panel3.add(button3,BorderLayout.EAST);
    panel3.add(panel5,BorderLayout.SOUTH);
    panel3.add(panel6,BorderLayout.WEST);
    label2.setText("聊天信息:");
    button3.setLabel("发送");
    msg_txt.setText("请输入聊天信息");
    //add actionlistener
    msg_txt.addKeyListener(this);      //"ctrl+enter" to send msg
    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
    
    ch1.addItemListener(this);
    ch2.addItemListener(this);
    ch3.addItemListener(this);
    cr1.addItemListener(this);
    cr2.addItemListener(this);
    cr3.addItemListener(this);
    cr4.addItemListener(this);
    list1.addItemListener(this);
    //set status
    ch1.setState(false);
    ch2.setState(false);
    ch3.setState(true);
    //other argument
    ctrldown=false;
    enterdown=false;
  }
  
  //keyEvent
  public void keyPressed(KeyEvent e)//use "ctrl+enter" to send message
  { if(e.getKeyCode()==e.VK_CONTROL)
    {  ctrldown=true; //press ctrl
    }
    if(ctrldown&&e.getKeyCode()==e.VK_ENTER)
    { enterdown=true; //press ctrl and then press enter
    }
  }
  public void keyReleased(KeyEvent e)
  { if(!enterdown&&e.getKeyCode()==e.VK_CONTROL)
      ctrldown=false; //just press ctrl for mistake
    if(ctrldown&&e.getKeyCode()==e.VK_ENTER)
    {  enterdown=false;
       ctrldown=false;  
       if(soc!=null)
       { StringBuffer msg;
         if(list1.getSelectedItem()==null)
         { msg=new StringBuffer("MSG:"
	                             +msg_txt.getFont().getStyle()+":"
	                             +msg_txt.getFont().getSize()+":"
	                             +color+":");        //定义并实例化一个字符缓冲存储发送的聊天信息
		                                //其中MSG为关键词
	       try
	       {        
	        String msgtxt=new String(msg_txt.getText());
	       }
	       catch(Exception e0){}
	     }
	     else
	     {  msg=new StringBuffer("MSGSEC: ");       //悄悄话关键字MSGSEC     
			String secname=list1.getSelectedItem();
			msg.append(secname+":"+msg_txt.getFont().getStyle()+":"
	                              +msg_txt.getFont().getSize()+":"
	                              +color+":");
	     }
	     ps.println(msg.append(msg_txt.getText()));          //用打印流发送聊天信息
	     ps.flush();
	     msg_txt.setText("");
  	  }
	}
  }
  public void keyTyped(KeyEvent e){}

  //button pressed event
  public void actionPerformed(ActionEvent e)    //事件触发代码
  { if(e.getActionCommand()=="连接")                //如果点击连接后
	{ if(soc==null)
      {  try
	     { soc=new Socket(InetAddress.getLocalHost(),2525);     //使用端口2525实例化一个本地套接字
		   System.out.println(soc);                             //在控制台打印实例化的结果
		   ps=new PrintStream(soc.getOutputStream());           //将ps指向soc的输出流
		   StringBuffer info=new StringBuffer("INFO: ");        //定义一个字符缓冲存储发送信息
			         //其中INFO为关键字让服务器识别为连接信息
			         //并将name和ip用":"分开,在服务器端将用一个
			         //StringTokenizer类来读取数据
		   String userinfo=name_txt.getText()+":"+InetAddress.getLocalHost().toString();
		   ps.println(info.append(userinfo));
		   ps.flush();
		   listen=new Listen(this,name_txt.getText(),soc);    //将客户端线程实例化  
		   listen.start();                                    //启动线程
		 }
		 catch(IOException e0)
		 { System.out.println("Error:"+e0);
		   disconnect();
		 }
	   }   //end of if
	 }//end of if
	 else if(e.getActionCommand()=="退出")                               //如果点击断开连接按钮则运行disconnect()
     { disconnect();
	 }
	 else if(e.getActionCommand()=="发送")                                 //如果点击发送按钮
	 { if(soc!=null)
	   { StringBuffer msg;                      //定义并实例化一个字符缓冲存储发送的聊天信息
	     if(list1.getSelectedItem()==null)
		 { msg=new StringBuffer("MSG:"+msg_txt.getFont().getStyle()+":"
	                                  +msg_txt.getFont().getSize()+":"
	                                  +color+":");        //定义并实例化一个字符缓冲存储发送的聊天信息
		                              //其中MSG为关键词
         } 
	     else	 
		 {  msg=new StringBuffer("MSGSEC: ");       //悄悄话关键字MSGSEC     
			String secname=list1.getSelectedItem();
			msg.append(secname+":"+msg_txt.getFont().getStyle()+":"
	                              +msg_txt.getFont().getSize()+":"
	                              +color+":");
		 }
		 try
		 {  String msgtxt=new String(msg_txt.getText());
		 }
		 catch(Exception e0){}
		 ps.println(msg.append(msg_txt.getText()));          //用打印流发送聊天信息
		 ps.flush();
		 msg_txt.setText("");
	   }
	 }
  }   //end of method actionPerformed
  
  //checkbox event&&list event
  public void itemStateChanged(ItemEvent e)
  { if(e.getSource()==list1)
    { int rv,index;
      String name=list1.getSelectedItem();
      index=list1.getSelectedIndex();
      if(select==null)
      { String info="要与"+name+"建立悄悄话模式?";
  	    String title="make sure";
        rv=JOptionPane.showConfirmDialog(this,info,title,
                  JOptionPane.OK_CANCEL_OPTION ); 
        if(rv==JOptionPane.OK_OPTION) 
        { select=name;
          selecti=index;
          StringBuffer msg=new StringBuffer("REQCON:");  	
          msg.append(name);
          ps.println(msg);
	      ps.flush();
	      System.out.println("request into secret");
	    }
	    else 
	    { list1.deselect(index);
	    }
	   }
	   else if(select.equals(name)) 
	   { String info="要与"+name+"退出悄悄话模式?";
  	     String title="make sure";
         rv=JOptionPane.showConfirmDialog(this,info,title,
                 JOptionPane.OK_CANCEL_OPTION ); 
         if(rv==JOptionPane.OK_OPTION) //send RESEXIT//退出悄悄话模式
         { select=null;
           selecti=-1;
           list1.deselect(index);
           StringBuffer msg=new StringBuffer("REQEXIT:");  	
           msg.append(name);
           ps.println(msg);
	       ps.flush();
	       System.out.println("request exit secret model");
	     }
	   }
	   else if(select!=null&&!(select.equals(name)))  //与另一用户
	   { String info="要与"+select+"退出悄悄话模式?";
	     info=info+"\n与"+name+"进入悄悄话模式?";
  	     String title="make sure";
         rv=JOptionPane.showConfirmDialog(this,info,title,
                  JOptionPane.OK_CANCEL_OPTION ); 
         if(rv==JOptionPane.OK_OPTION) //send RESEXIT//退出悄悄话模式
         { StringBuffer msg1=new StringBuffer("REQEXIT:");  	
           msg1.append(select);
           ps.println(msg1);
	       ps.flush();
	       System.out.println("request exit secret model");
	       select=name;
	       selecti=index;
	       StringBuffer msg2=new StringBuffer("REQCON:");  	
           msg2.append(name);
           ps.println(msg2);
	       ps.flush();

⌨️ 快捷键说明

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