Chat Application Using Java Part - 1

Posted on the 01 August 2013 by Abhishek Somani @somaniabhi
This tutorial is about creating a chat application using java RMI , Socket connection and java swing .This is the first part of this two part tutorial series . First let’s take a look at the functionalities we will be creating in this chat application. This chat application will have two parts ( client and server ) . The server will be running as rmi server. Whenever a client connects to server , it will first authenticate the client (client can register himself on the server ) After successful authentication , the client will be shown friend’s list , so that he can chat to his friends. Whenever a friend becomes online or offline , the client is notified and friends list changes dynamically . Server stores user list and friends list in it's internal database. When the client connects to rmi server , it provides it’s ip also which is saved by rmi server. When a client start chat with online friend , the rmi server issues a remote call to start a socket connection to transfer chat messages . So rmi server here does not store or save chat . The chat messages are transferred directly between the clients by using socket connection between them. In this part of tutorial , we will create a basic gui using java swing. so these are our model classes :
 
/**
 * Application Name :- Let's Chat
 * 
 * @(#)ClientApplication.java
 *
 *
 * @author abhishek somani
 * @version 1.00 2008/4/7
 *
 * Providing the Main userInterface or the Login window for the user
 * to use this application
 */

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class ClientApplication extends JFrame implements ActionListener ,MouseListener //, MouseMotionListener
{
 // public and private variables of the class
 private JTextField username;
 private JPasswordField password;
 private JLabel user, pass,  error, logo, forgotpassword, register;
 private JButton enterBtn;
 private URL url;
 public JPanel Ippanel , Serveranspanel , buttonpannel, registerpanel, forgotpasswordpanel;
 public JPanel passwordpannel, usrnamepannel, usrfieldpannel, passfieldpannel, btnpannel, errorpannel;
 WindowUtilities Look;
 Toolkit kit;
 Container contentpane;
 private int screenheight,screenwidth;
 private Login obj;
 
 final Color COLOR_NORMAL    = Color.BLUE;
   final Color COLOR_HOVER     = Color.RED;
   final Color COLOR_ACTIVE    = COLOR_NORMAL;
   final Color COLOR_BG_NORMAL = Color.LIGHT_GRAY;
   final Color COLOR_BG_ACTIVE = Color.LIGHT_GRAY;
   Color mouseOutDefault;
 

 // main class for just checking the frame without any other connection
  public static void main(String [] args)
 {
     
  ClientApplication f = new ClientApplication();
  f.setVisible(true);
  f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
    public ClientApplication()
    {
     
     // Look and feel class of window utility
     Look = new WindowUtilities();
     Look.setNativeLookAndFeel();
     addWindowListener(new ExitListener());
     
     // getting the Dimension of the Screen from system
     // in which this application is running 
     kit = Toolkit.getDefaultToolkit();
     Dimension screensize = kit.getScreenSize();
  screenheight = screensize.height;
  screenwidth = screensize.width;
  
  //setting the frame on the right hand side corner of the screen
  setSize(screenwidth/4  , (screenheight-50));
  setLocation((screenwidth-screenwidth/4) , 0);
  setResizable(true);
  setVisible(true); 
  contentpane = getContentPane();
  contentpane.setLayout(new GridLayout(3,1));
  
  // setting the font for any text field of frame
  java.awt.Font font = new java.awt.Font("Dialog",Font.BOLD,14);
  
  // creating one of the main panel
  Ippanel = new JPanel();
  Ippanel.setBorder(BorderFactory.createTitledBorder("Login"));
  Ippanel.setLayout(new GridLayout(6,1));    
  
  // creating and adding username label in usernamepanel
  usrnamepannel = new JPanel();
  user = new JLabel("Username: ");
  user.setFont(font);
  usrnamepannel.add(user,BorderLayout.CENTER);
  Ippanel.add(usrnamepannel, BorderLayout.CENTER);
  
  // creating and adding username textfield in usrfieldpanel
  usrfieldpannel = new JPanel();
  usrfieldpannel.add(username = new JTextField(20), BorderLayout.CENTER);
  Ippanel.add(usrfieldpannel, BorderLayout.CENTER);
  
  // creating and adding password label in passwordpanel  
  passwordpannel = new JPanel();
  pass = new JLabel("Password: ");
  pass.setFont(font);
  passwordpannel.add(pass, BorderLayout.CENTER);
  Ippanel.add(passwordpannel,BorderLayout.CENTER);
  
  // creating and adding password textfield in passfieldpanel
  passfieldpannel = new JPanel();
  passfieldpannel.add(password = new JPasswordField(20),BorderLayout.CENTER );
  Ippanel.add(passfieldpannel, BorderLayout.CENTER);
  
  // error label in case of username and password doesn't match
  errorpannel = new JPanel();
  error = new JLabel("Username and Password doesn't match");
  error.setFont(font);
  error.setVisible(false);
  error.setForeground(Color.RED);
  error.setOpaque(true);
  errorpannel.add(error,BorderLayout.CENTER);
  Ippanel.add(errorpannel, BorderLayout.CENTER);
  
  // creating and adding login button in btnpanel
  btnpannel = new JPanel();
  enterBtn = new JButton("Login");
  enterBtn.setFont(font);
  btnpannel.add(enterBtn, BorderLayout.CENTER);
  Ippanel.add(btnpannel, BorderLayout.CENTER);
  
  // adding logo of the Let's chat to the frame
  Serveranspanel = new JPanel();
  Serveranspanel.setBorder(BorderFactory.createLineBorder (Color.blue, 2));    
  Serveranspanel.setBackground(Color.CYAN);
  ImageIcon letchaticon = new ImageIcon("images/llo.jpg");
  logo = new JLabel();
  logo.setIcon(letchaticon);
  logo.setToolTipText("Welcome to Let's Chat Application");
  Serveranspanel.add(logo);
  
  // creating and adding register label 
  registerpanel = new JPanel();
     register = new JLabel("Register");
     register.setFont(font);
     register.addMouseListener(this);
     registerpanel.add(register, BorderLayout.CENTER);
     
     // creating and adding forgetpassword label
     forgotpasswordpanel = new JPanel();
     forgotpassword = new JLabel("Forgot Password");
     forgotpassword.setFont(font);
     forgotpassword.addMouseListener(this);
     forgotpasswordpanel.add(forgotpassword, BorderLayout.CENTER);
     
  buttonpannel = new JPanel();
  buttonpannel.setLayout(new GridLayout(8,1)); 
  buttonpannel.add(registerpanel,BorderLayout.CENTER);
  buttonpannel.add(forgotpasswordpanel,BorderLayout.CENTER);
  
  // adding all the pannels to ContentPane
  contentpane.add(Serveranspanel);
  contentpane.add(Ippanel);
  contentpane.add(buttonpannel);
  
  // add Action listener to the login button
  enterBtn.addActionListener(this);
  enterBtn.setToolTipText("Please enter username and password then press this button");
 
    }
    
    
    // action againist login button click
    public void actionPerformed(ActionEvent ae)
    {
     //System.out.println("Action Performed");
       
       boolean flag;
       
     if (ae.getActionCommand().equals("Login"))
     {
      JButton clickedbutton = (JButton)ae.getSource();
      if(clickedbutton == enterBtn)
      {
       String us = username.getText();
       String ps = password.getText();
       // validating either username and password fields are not empty
       if(us.equals(""))
       {
        error.setText("Please enter the username");
        error.setVisible(true);
            
       }
       else if(ps.equals(""))
       {
        error.setText("Please enter the password");
        error.setVisible(true);
            
       }
       else
       {       
        obj=new Login();
        try
        {
         //Get an instance of InetAddress for the local computer
      InetAddress inetAddress = InetAddress.getLocalHost();
    
      //Get a string representation of the ip address
      String ipAddress = inetAddress.getHostAddress();
    
    
      //Print the ip address
      //System.out.println(ipAddress);
         flag = obj.login(us,ps,ipAddress);
         if(flag == true)
         {
          //System.out.println("Frame Repainted");
          dispose();
                  
         }
         if(flag == false)
         {
          error.setText("Username and Password doesn't match");
          error.setVisible(true);
         }
        }
        catch(Exception e)
        {
         System.out.println(e.getMessage());
        }
       }
       
      }
      
     }
    }
    
    // action against mouse click on register to open the register for
    // let's chat application and forgetpassword for existing user who
    // forget their passwords
    public void mouseClicked(java.awt.event.MouseEvent me)
 {

  if(me.getSource() instanceof JLabel)
  {

   JLabel clicked = (JLabel)(me.getSource());
   setForeground(COLOR_ACTIVE);
         mouseOutDefault = COLOR_ACTIVE;
   if(clicked == register)
   {
       //System.out.println("Register Clicked");
                       //you can create a simple web app where user where user can register themselves and give link here
       String url = "http://resigisetrurl/chat/register.html";
       String os = System.getProperty("os.name").toLowerCase();
       Runtime rt = Runtime.getRuntime();
       try
       {
              if (os.indexOf( "win" ) >= 0)
              {
                 String[] cmd = new String[4];
                 cmd[0] = "cmd.exe";
                 cmd[1] = "/C";
                 cmd[2] = "start";
                 cmd[3] = url;
                 rt.exec(cmd);
              }
              else if (os.indexOf( "mac" ) >= 0)
              {
                  rt.exec( "open " + url);
              }
              else
              {
                 //prioritized 'guess' of users' preference
                 String[] brwsers = {"epiphany", "firefox", "mozilla"}; 
                 StringBuffer cmd = new StringBuffer();
                 for (int i=0; i= 0)
              {
                 String[] cmd = new String[4];
                 cmd[0] = "cmd.exe";
                 cmd[1] = "/C";
                 cmd[2] = "start";
                 cmd[3] = url;
                 rt.exec(cmd);
              }
              else if (os.indexOf( "mac" ) >= 0)
              {
                  rt.exec( "open " + url);
              }
              else
              {
                 //prioritized 'guess' of users' preference
                 String[] brwsers = {"epiphany", "firefox", "mozilla", "konqueror", "netscape","opera","links","lynx"};
 
                 StringBuffer cmd = new StringBuffer();
                 for (int i=0; i<brwsers.length; i++)
                  cmd.append( (i==0  ? "" : " || " ) + brwsers[i] +" \"" + url + "\" ");
 
                 rt.exec(new String[] { "sh", "-c", cmd.toString() });
                               
              }
       }
       catch(Exception e)
       {
        System.out.println("error occured in opening browser");
       }
      }
     }
    }
    
    public void mouseExited(MouseEvent me)
    {
  setForeground(mouseOutDefault);
        setBackground(COLOR_BG_NORMAL);
        Cursor cursor = getCursor();
        setCursor(cursor.getDefaultCursor());
        //System.out.println("Mouse Exited");
    }
    public void mouseReleased(MouseEvent me) 
    {
        //System.out.println("Mouse Released");
    }
      
    public void mousePressed(MouseEvent me)
    {
      mouseOutDefault = COLOR_ACTIVE;
      //System.out.println("Mousepressed");
    }
      
    public void mouseEntered(MouseEvent me) 
    {
     setForeground(Color.RED);
        setBackground(COLOR_BG_ACTIVE);
        Cursor cursor = getCursor();
        setCursor(cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
       // System.out.println("Mouse Entered");
    }
    
}
Here , we have created Register and forgot password buttons , which will open browser and point to your web app , where you have defined mechanism for registering a user and forgot password mechanism. Other part of code is quite self explanatory where we have created panels and arranged them in proper way . Post your comments and suggestions !!