首页
java聊天室案例
日期:2021-10-25 12:13  点击:158
java 案例 聊天室,定义全局变量或成员变量
package dfwewvw;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import javax.swing.*;
import java.sql.*;
public class reg extends JFrame  {  //定义全局变量或成员变量  private JButton reg=new JButton("注册新用户");//添加新用户注册按钮  private JButton login=new JButton("登录");//添加登录按钮  private JButton regsave=new JButton("确定");//添加确定按钮  private JLabel usertext=new JLabel("用户名");//添加用户名输入栏  private JLabel truenametext=new JLabel("姓名");//添加姓名输入栏  private JLabel passtext=new JLabel("密码");//添加密码输入栏  private JLabel rpasstext=new JLabel("确认密码");//添加添加密码确认栏  private JTextField userfield=new JTextField(40);//用户名输入栏大小  private JTextField truenamefield=new JTextField(40);//姓名输入栏大小  private JPasswordField passfield=new JPasswordField(40);//密码输入栏大小  private JPasswordField rpassfield=new JPasswordField(40);//密码确认输入栏大小  private JPanel up=new JPanel();  private JPanel down=new JPanel(){  protected void paintComponent(Graphics g) {             super.paintComponent(g);             ImageIcon img = new ImageIcon(reg.class.getResource("这个是聊天室.jpg"));              img.paintIcon(this, g, 0, 0);       }   };  private JPanel center=new JPanel();  private JDialog dialog;  private JLabel welcome=new JLabel("欢迎来到聊天室");//添加欢迎栏目  private JButton update=new JButton("修改密码");//添加修改密码按钮  private JButton chart=new JButton("开始聊天");//添加聊天室进入按钮  private JFrame f;  private String usersuc;    reg(){  reggui();  reglistion();  }  //注册图形界面  void reggui(){  up.setLayout(new GridLayout(2,2));  up.add(usertext);up.add(userfield);  up.add(passtext);up.add(passfield);  down.add(reg);down.add(login);  center.add(welcome);center.add(update);  center.add(chart);    f=new JFrame("注册窗口");  f.setSize(400,300);  f.setLocation(400,300);  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  f.setLayout(new BorderLayout());  f.add(up,BorderLayout.CENTER);  f.add(down,BorderLayout.SOUTH);  f.add(center,BorderLayout.NORTH);  f.setVisible(true);  center.setVisible(false);  }  //注册监听  void reglistion() {  reg.addActionListener(new ActionListener() {   public void actionPerformed(ActionEvent e) {  dialog = new JDialog(reg.this, true );   dialog.setTitle("注册用户名");  dialog.setSize(400, 300);  dialog.setLocation(60, 60);  dialog.setLayout(new GridLayout(5,2));  dialog.add(truenametext);dialog.add(truenamefield);  dialog.add(usertext);dialog.add(userfield);  dialog.add(passtext);dialog.add(passfield);  dialog.add(rpasstext);dialog.add(rpassfield);  dialog.add(regsave);  dialog.setVisible(true);  }  }); //按钮注册弹窗  //注册提交数据库  regsave.addActionListener(new ActionListener() {   public void actionPerformed(ActionEvent e) {  String u=userfield.getText();  String p=passfield.getText();  String rp=passfield.getText();  String name=truenamefield.getText();  if(u.length()<6 ||u.length()>10) {  message("用户名错误");  return;  }  if(!p.equals(rp)) {  message("两次密码不一样");  return;  }  int resutl=sql(u,p,name,"find");  if(resutl==1) {  message("用户名存在");  return;  }  sql(u,p,name,"insert");      welcome.setText("欢迎您:"+u);      f.setTitle("欢迎您:"+u);  dialog.dispose();  up.setVisible(false);  down.setVisible(false);  center.setVisible(true);  usersuc=u;  message("注册成功");  }  });    //登陆  login.addActionListener(new ActionListener() {   public void actionPerformed(ActionEvent e) {  String u=userfield.getText();  String p=passfield.getText();   String name=null;  int result=sql(u,p,name,"login");  if(result==1) {   welcome.setText("欢迎您:"+u);   f.setTitle("欢迎您:"+u);   up.setVisible(false);   down.setVisible(false);   center.setVisible(true);   usersuc=u;  }else {   message("用户名或密码错误");  }  }  });    //进入聊天室  chart.addActionListener(new ActionListener() {   public void actionPerformed(ActionEvent e) {  new chart(usersuc);  }  });    }      int sql(String u,String p,String name,String action) {  Statement stmt = null;    Connection conn = null;    ResultSet rs = null;  int result=0;  try {  // 1. 注册数据库的驱动  Class.forName("com.mysql.jdbc.Driver");  // 2.通过DriverManager获取数据库连接  String url = "jdbc:mysql://localhost:3306/test";  String username = "root";  String password = "root";  conn = DriverManager.getConnection(url, username, password);  // 3.通过Connection对象获取Statement对象  stmt = conn.createStatement();  // 4.使用Statement执行SQL语句。  System.out.print(action);  if(action.equals("insert")) {  String sql = "INSERT INTO user(user,pass,truename) value('"+u+"','"+p+"','"+name+"')";  stmt.executeUpdate(sql);  }else if(action.equals("find")){  String sql = "select * from user where user='"+u+"' ";  rs = stmt.executeQuery(sql);  if(rs.next()) {  result=1;  }  }else if(action.equals("login")){  String sql = "select * from user where user='"+u+"' and pass='"+p+"' ";  rs = stmt.executeQuery(sql);  if(rs.next()) {  result=1;  }  }else if(action.equals("update")){  String sql = "update user set pass='"+p+"' where user='"+u+"' ";  stmt.executeUpdate(sql);   }    } catch (Exception e) {  e.printStackTrace();  }  return result;  }    void message(String str){  JDialog dialog = new JDialog(reg.this, true );  JOptionPane.showMessageDialog(dialog, str,"dsfad",JOptionPane.ERROR_MESSAGE);  }  public static void main(String[] args) {  new reg();  }  public static class cilent  extends JFrame {  private JButton send; //添加发送按钮  private JButton btnclear; //添加清楚按钮  private JButton exit; //添加删除按钮  private JPanel up; //添加一个内容为up的面板容器  private JPanel center; //添加一个内容为center的面板容器  private JPanel down; //添加一个内容为down的面板容器  private JTextArea inputTextArea;//输入  private JTextArea showTextArea;//显示  private JComboBox userlist;  private JButton serverjoin; //添加一个按钮为serverjoin  private JButton serverjoinsubmit=new JButton("确定");; //将上面的这个按钮定义为确定  private JLabel serverjoinlable; //添加一个内容为serverjoinlable的面板容器  private JTextField username; //添加一个文框用于username  private JTextField ip; //添加一个文框用于ip  private JTextField port; //添加一个文框用于port  private Socket client; //定义一个client包  private String userid;  private InetAddress ips;  private int ports;    //客服端   cilent(){  gui();//图形界面  listion();//按钮监听  flashuser();//刷新在线人数   }    void gui(){  //窗体  JFrame f=new JFrame("客户端");//添加名字为客户端  f.setSize(800,500); //设置大小  f.setLocation(300,100); //设置弹出窗口的位置  up=new JPanel() ;  center=new JPanel() ;  down=new JPanel() ;  inputTextArea=new JTextArea(5,50);//设置输入框大小  showTextArea=new JTextArea(20,50);//设置显示框大小  showTextArea.setEditable(false);  serverjoinlable=new JLabel("未连接服务器") ;  down.add(serverjoinlable);  send=new JButton("发送") ;//将这个按钮名为“发送”  btnclear=new JButton("清屏") ;//将这个按钮名为“清屏”  exit=new JButton("退出") ;//将这个按钮名为“退出”  serverjoin=new JButton("连接服务器") ;  down.add(serverjoin);  userlist=new JComboBox();  userlist.addItem("所有人");  up.add(new JScrollPane(showTextArea));  center.add(inputTextArea);  down.add(userlist); //将按钮添加进面板  down.add(send); //将按钮添加进面板  down.add(btnclear); //将按钮添加进面板  down.add(exit); //将按钮添加进面板  f.setLayout(new BorderLayout());  f.add(up,BorderLayout.NORTH); //设置这个面板的位置   f.add(center,BorderLayout.CENTER); //设置这个面板的位置  f.add(down,BorderLayout.SOUTH); //设置这个面板的位置  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   f.setVisible(true); //将这个为可视  }    //清屏   //连接服务器监听  void listion() {  serverjoin.addActionListener(new ActionListener() {   public void actionPerformed(ActionEvent e) {  JDialog dialog = new JDialog(cilent.this, true );  dialog.setLayout(new GridLayout(4,2));  dialog.setTitle("服务器连接");  dialog.setSize(300, 200);  dialog.setLocation(50, 50);  JLabel usernametext=new JLabel("用户名");  JLabel iptext=new JLabel("IP");  JLabel porttext=new JLabel("端口");  username=new JTextField();  ip=new JTextField();  port=new JTextField();  dialog.add(usernametext);  dialog.add(username);  dialog.add(iptext);  dialog.add(ip);  dialog.add(porttext);  dialog.add(port);  dialog.add(serverjoinsubmit);  dialog.setVisible(true);  }  });    //服务器连接输入ip端口并提交  serverjoinsubmit.addActionListener(new ActionListener() {   public void actionPerformed(ActionEvent e) {  serverjoinlable.setText("已连接服务器");  try {  ips = InetAddress.getByName(ip.getText());  ports=Integer.parseInt(port.getText());  client=new Socket(ips,ports);  PrintWriter writer = new PrintWriter(client.getOutputStream());  userid=username.getText();  String a=userid+"@@"+"reg";  writer.println(a);            writer.flush();   } catch (Exception e1) {  e1.printStackTrace();  }  }  });    //发送聊天内容  send.addActionListener(new ActionListener() {   public void actionPerformed(ActionEvent e) {  try {  //client=new Socket(ips,ports);    PrintWriter writer = new PrintWriter(client.getOutputStream());  String a=userid+"@"+inputTextArea.getText()+"@"+userlist.getSelectedItem();  writer.println(a);            writer.flush();   } catch (Exception e1) {  e1.printStackTrace();  }  }  });    //退出按钮监听  exit.addActionListener(new ActionListener(){          public void actionPerformed(ActionEvent e) {              // TODO Auto-generated method stub              System.exit(0);          }      }      );    }  //刷新按钮监听  void flashuser(){   new Thread() {    //多线程方法  public void run() {       //多线程的RUN方法  while(true) { //while的一个死循环  System.out.println(client);  if(client!=null) { //if的一个判断是否为空      try {  BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream())); //整体意思就是用InputStreamReader这个中介把System.in这个字节流转换成字符流BufferedReader  String line=r.readLine();  String[] arr=line.split("@"); //用@符号来相互隔开  //null@aaaa@userlist  if(arr[arr.length-1].equals("userlist")) { //判断他的最后一位的长度—1是否等于这个userlist  for(String user:arr) {  if(!user.equals("null")&&!user.equals("userlist")) {  userlist.addItem(user);       }  }  }else if(arr[arr.length-1].equals("群发聊天")) {  showTextArea.append(arr[0]+arr[1]+"\n");  }else {      showTextArea.append(arr[0]+arr[1]+arr[2]+"\n");  }     }catch(Exception e) {  e.printStackTrace();     }                 }             }  }     }.start();  }    //先运行主函数  public static void main(String[] args) {  new cilent();  }  }
}

上一篇· java在线聊天室服务端Server类的创建    下一篇·关于java的InetAddress连接
最新文章
热门文章
关于网站  |  联系我们  |  网站地图  | 
2021-10-25 12:13
Powered by edu63.com
首页 刷新 顶部