Online Chat Application in java Netbeans

This is an overview of an online chat application build in java netbeans. The app connects to remote database and enables us to chat with online people. This can be considered as a class 12 project. And this is clearly not the way, a real time chat app is implemented. But it will give you a basic overview of how we can implement chat with just MySQL and java.

If you are interested in building a real time chat, then do give this a try.

[wpi_designer_button text=’Download’ link=’https://github.com/arjunsk/javaOnlineChat’ style_id=’48’ icon=’github’ target=’_blank’]

Before you continue, please make sure that you have read:

How to send variable values between 2 jFrames in Java Netbeans

Here, I have used the free remote database service provider : https://www.db4free.net/about.php

You can register a free account. Now replace dbuser, dbpass, and dbname with your username, password and database name.

LEVEL 1 [ BASICS ] :-

[color-box ]  LOGIN SCREEN [/color-box]

login

  • Used AbsoluteLayout to add the background and position the UI elements.
  • Here login button is actually a jLabel with image.

Login Button:

private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {                                     

        String username = tfuser.getText();
        String password = tfpass.getText();

        if (username.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Enter the Username");
        } else if (password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Enter the Password");
        } else {

            try {
                Class.forName("java.sql.DriverManager");
                // the part to edit 
                Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://db4free.net:3306/dbname", "dbuser", "dbpass");

                Statement stmt1 = (Statement) con.createStatement();
                String query1 = "SELECT userid,enterinfo, password,verify ,md5('" + password + "') as curpass FROM registration WHERE username='" + username + "';";
                ResultSet rs1 = stmt1.executeQuery(query1);

                if (rs1.next()) {
                    String pass = rs1.getString("password");
                    String curpass = rs1.getString("curpass");
                    int verify = rs1.getInt("verify");
                    int enterinfo = rs1.getInt("enterinfo");
                    int userid = rs1.getInt("userid");

                    if (pass.equals(curpass) && (verify == 1)) {
                        JOptionPane.showMessageDialog(this, "You are IN");

                        if (enterinfo == 1) {
                            try {
                                Statement stmt2 = (Statement) con.createStatement();
                                String query2 = "UPDATE onlinebud SET login=1,usertime=now() where userid='" + userid + "';";
                                stmt1.executeUpdate(query2);
                            } catch (Exception e) {
                                JOptionPane.showMessageDialog(this, e.getMessage());
                            }

                            // go to online buddy
                            String info[] = new String[2];
                            info[0] = tfuser.getText();
                            info[1] = "" + userid;
                            onlinebuddy.main(info);
                            this.setVisible(false);

                        } else {
                            // go to enterinfo
                            String info[] = new String[2];
                            info[0] = tfuser.getText();
                            info[1] = "" + userid;
                            EnterInfo.main(info);
                            this.setVisible(false);
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Invalid Username Or Password");
                    }

                } // if (rs1.next()&&rs2.next())
                else {
                    JOptionPane.showMessageDialog(this, "User does not exist");
                }

                con.close();
            } // try
            catch (Exception e) {
                JOptionPane.showMessageDialog(this, e.getMessage());

            }// catch
        }// if username and password not empty     


        // TODO add your handling code here:
    }

Register Button :

    private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {                                     
        this.setVisible(false);
        new Register().setVisible(true);
    }

[color-box ]  REGISTER SCREEN  [/color-box]

register

Register Button :

    private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {                                     


 String name,username,password,confirmpass,email;        
        
name=jTextField2.getText();
username=jTextField1.getText();
password=jPasswordField2.getText();
confirmpass=jPasswordField1.getText();
email=jTextField5.getText();

if (name.isEmpty() || username.isEmpty() || password.isEmpty() || confirmpass.isEmpty() || email.isEmpty())
{
    JOptionPane.showMessageDialog(this,"Complete All The Fields");
}

else if(!(confirmpass.equals(password)))
{
JOptionPane.showMessageDialog(this,"Passwords mismathced");
}   
else{    
try{
Class.forName("java.sql.DriverManager");
// the part to edit 
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://db4free.net:3306/dbname", "dbuser", "dbpass");



Statement stmt2=(Statement) con.createStatement();
String query2="SELECT userid FROM registration WHERE username='"+username+"';";
ResultSet rs2=stmt2.executeQuery(query2);

if (rs2.next()){
    
 JOptionPane.showMessageDialog(this,"User Already Exist");   
}

else{


Statement stmt1=(Statement) con.createStatement();
String query1="INSERT INTO registration VALUES( 0,'"+username+"',md5('"+password+"'),123,'"+email+"','"+name+"','123',1,123);";
stmt1.executeUpdate(query1);


Statement stmt4=(Statement) con.createStatement();
String query4="SELECT userid  FROM registration  where  username= '"+username+"';";
ResultSet rs4=stmt4.executeQuery(query4);

if (rs4.next()){ 
int userid = rs4.getInt("userid");      
Statement stmt3=(Statement) con.createStatement();
String query3="INSERT INTO onlinebud VALUES( 0,'"+userid+"','"+username+"',curtime(),0,0);";
stmt3.executeUpdate(query3);    
}





JOptionPane.showMessageDialog(this,"Registration Completed");

this.setVisible(false);
new loginpage().setVisible(true);
 
}
con.close();
}


catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}// catch

}// else

 
        // TODO add your handling code here:
    }

Back Button :

    private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {                                     
 this.setVisible(false);       
 new loginpage().setVisible(true);  
 
 // TODO add your handling code here:
    }

[color-box ]  PROFILE PAGE  [/color-box]

profile

Profile page loads information about the user when the form is activated.

 private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
   
try{
Class.forName("java.sql.DriverManager");
// the part to edit 
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://db4free.net:3306/dbname", "dbuser", "dbpass");

Statement stmt1=(Statement) con.createStatement();
String query1="SELECT name,displayname, gender,dob ,personalmessage,country,membersince  FROM registration , enterinfo where  enterinfo.userid=registration.userid and registration.userid= '"+userid+"';";
ResultSet rs1=stmt1.executeQuery(query1);

if (rs1.next()){    
String name = rs1.getString("name");
String displayname = rs1.getString("displayname");
String gender = rs1.getString("gender");
String dob = rs1.getString("dob");
String personalmessage = rs1.getString("personalmessage");
String country = rs1.getString("country");
String membersince = rs1.getString("membersince");



jTextField2.setText(""+name);
jTextField4.setText(""+displayname);
jTextField3.setText(""+gender);
jTextField6.setText(""+dob);
jTextField8.setText(""+personalmessage);
jTextField7.setText(""+country);
jTextField5.setText(""+membersince);


con.close();
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, "Error");

}

Edit Button :

    private void jLabel11MouseClicked(java.awt.event.MouseEvent evt) {                                      
     
 String info[]=new String[2];
 info[0]=username;
 info[1]=userid;
 updateEnterInfo.main(info);
 
 this.setVisible(false);
    }

OK Button :

    private void jLabel10MouseClicked(java.awt.event.MouseEvent evt) {                                      

        this.setVisible(false);
        
        // TODO add your handling code here:
    }

[color-box ]  ONLINE USERS PAGE  [/color-box]

online users

Loads the list of online users when the page is activated.

private void formWindowActivated(java.awt.event.WindowEvent evt) {                                     
 // the part where list is set values
/**************************************************************/
        
        jList2.setVisible(false);
        //start of main code                
        try {
            Class.forName("java.sql.DriverManager");
             // the part to edit 
            Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://db4free.net:3306/dbname", "dbuser", "dbpass");
            Statement stmt1 = (Statement) con.createStatement();
            String query1 = "SELECT onlinebud.userid,displayname  FROM onlinebud , enterinfo where  enterinfo.userid=onlinebud.userid and onlinebud.login=1  and onlinebud.userid not in (" + userid + ") ;";
            ResultSet rs1 = stmt1.executeQuery(query1);
       
            // for intilising the size of the array
            int arraysize = 10;
            Statement stmt2 = (Statement) con.createStatement();
            String query2 = "SELECT count(userid) as arraysize from onlinebud;";
            ResultSet rs2 = stmt2.executeQuery(query2);
            if (rs2.next()) {arraysize = rs2.getInt("arraysize");}
             // end of arraysize
            // creating a string array for storing the list items from database
            String arr1[] = new String[arraysize];
            String arr2[] = new String[arraysize];


            
                  // index is the index of array 
                 // userid2 and userid3 
                // displayname is obtained from the database
               // userid2 is the userid of displaynames in int as got from the database 
              // userid3 is ther userid of displayname in string so that it can be put in the list
                int index = 0, userid2;       // >> all this  is neccessary <<
                String displayname, userid3; //>> all this  is necessary <<
                
                while (rs1.next()) {
                // userid2 is the userid of displaynames in int as got from the database    
                userid2 = rs1.getInt("userid");
                // userid3 is ther userid of displayname in string so that it can be put in the list
                userid3 = "" + userid2;
                displayname = rs1.getString("displayname");

                // array is created based on the two results ie userid3 and displayname
                arr1[index] = displayname;
                arr2[index] = userid3;

                ++index;}

            // the part which sets the model in the list (i am using 2 list boxes to collect data from database and store two values in the list box)
            jList1.setListData(arr1);
            jList2.setListData(arr2);

            con.close();} 
            catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage());}             // TODO add your handling code here:
    
 // the part where list is set values
/**************************************************************/
    }

When the user clicks any online user from the  Online user list

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {                                    
// the part where list values create a dalogue and textarea in jtabbeded panel 
/**************************************************************/  
        
        int userid4index;String userid4, username4;
        // sending the values to the chat dailog box

        //using selected values for username and userindex with 2 jLists
        username4 = (String) jList1.getSelectedValue(); // reciver name <<<<
        userid4index = jList1.getSelectedIndex(); // reciever jList(Name) index
        jList2.setSelectedIndex(userid4index); // receivers jList (userid) is selected
        userid4 = (String) jList2.getSelectedValue(); // recievers userid <<<<

        // if no item is selected for eg: if null in the list is selected (nothing happens)
        if (userid4 == null) {} 
        else {
            // unique tabid for all tabs

            String tabidis = userid4; // this will be set to the tab

            // showing the dailoge box        
            jDialog1.setSize(674, 530);
            jDialog1.setVisible(true);


            if (jTabbedPane1.indexOfTab(username4) != -1 ) {} // check if a chat box with the displayname is already present or not            
            else{
                JScrollPane panel2 = new JScrollPane();
                panel2.setName(tabidis);
         
                
               chattable = new JTable();
               chattable.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"Messages"}));
               panel2.setViewportView(chattable);
               chattable.setShowGrid(false);
             
                
               jTabbedPane1.add(username4, panel2);
                
                
                
         /* normal loading of all the messages********
        ********************************************/
        send3=tabidis; // the user id of reciever
        DefaultTableModel model = (DefaultTableModel) chattable.getModel();
        
        try {
            Class.forName("java.sql.DriverManager");
             // the part to edit 
            Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://db4free.net:3306/dbname", "dbuser", "dbpass");
            Statement stmt6 = (Statement) con.createStatement();
            String query6 = "SELECT *  FROM chatmessages where  ((recieve= '" + userid + "'  && send='" + send3 + "')or(recieve= '" + send3 + "'  && send='" + userid + "'));";
            ResultSet rs6 = stmt6.executeQuery(query6); // the above is used to get only the message between sender & reciver. note && is used instead of and

            String message, sender1;
            if (rs6.next()) {
           
                
            int rows=model.getRowCount();
            if (rows>0){for (int i=0; i<rows; i++){model.removeRow(0);}}
         
           
            while (rs6.next()) {
                    message = rs6.getString("message");
                    sender1 = rs6.getString("sender1"); // to show who sends the message 
                    String finalmessage = sender1 + " : " + message + "\n\n";
                    model.addRow (new Object[] {finalmessage});
                    
            } // the while part
            } // normal rs.next
            
            con.close();} // the try part                     
            catch (Exception e) {JOptionPane.showMessageDialog(null, e.getMessage());}
            // ***************end of that normal loading ****************************//

        }
        }
 // the part where list values create a dalogue and textarea in jtabbeded panel 
/**************************************************************/ 
    }

[color-box ]  UPDATE PROFILE INFO PAGE  [/color-box]

update

Go Button :

    private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {                                     
        
        String displayname,gender,dob,personalmessage,country;
        
        displayname=jTextField2.getText();
        gender= ""+ jComboBox1.getSelectedItem();
        dob=jComboBox4.getSelectedItem()+"/"+ jComboBox3.getSelectedItem()+"/"+ jComboBox2.getSelectedItem();
        personalmessage=jTextField3.getText();
        country=""+jComboBox5.getSelectedItem();
        
        
        if (displayname.isEmpty() || gender.isEmpty() || dob.isEmpty() || personalmessage.isEmpty() || country.isEmpty())
            JOptionPane.showMessageDialog(this,"Complete All The Fields");
        
        
        else{
            
            try{
                Class.forName("java.sql.DriverManager");
                // the part to edit
                Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://db4free.net:3306/dbname", "dbuser", "dbpass");
                
                Statement stmt3=(Statement) con.createStatement();
                String query3="Select * from enterinfo where displayname='"+displayname+"' and userid not in("+userid+");";
                ResultSet rs3=stmt3.executeQuery(query3);
                if(rs3.next()){JOptionPane.showMessageDialog(null,"Sorry! Displayname Exists");}

               else{
                Statement stmt1=(Statement) con.createStatement();
                String query1="UPDATE enterinfo SET displayname='"+displayname+"',gender='"+gender+"',dob='"+dob+"',personalmessage='"+personalmessage+"',country='"+country+"' where userid='"+userid+"';";
                stmt1.executeUpdate(query1);
   
                
               JOptionPane.showMessageDialog(this,"Info Updated");
                
                
                this.setVisible(false);
                con.close();  
            }
            }
            catch(Exception e){
                JOptionPane.showMessageDialog(this,e.getMessage());
                
            }// catch
            }// if username and password not empty
        
        // TODO add your handling code here:
}

[color-box ]  MYSQL DATABASE  [/color-box]

--
-- Table structure for table `chatmessages`
--

CREATE TABLE `chatmessages` (
  `send` varchar(11) DEFAULT NULL,
  `recieve` varchar(11) DEFAULT NULL,
  `message` varchar(300) DEFAULT NULL,
  `sendername` varchar(20) DEFAULT NULL,
  `recievername` varchar(20) DEFAULT NULL,
  `sender1` varchar(20) DEFAULT NULL,
  `messageid` varchar(200) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `enterinfo`
--

CREATE TABLE `enterinfo` (
  `displayname` varchar(50) DEFAULT NULL,
  `gender` varchar(5) DEFAULT NULL,
  `dob` varchar(20) DEFAULT NULL,
  `personalmessage` varchar(200) DEFAULT NULL,
  `country` varchar(100) DEFAULT NULL,
  `membersince` varchar(50) DEFAULT NULL,
  `userid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `onlinebud`
--

CREATE TABLE `onlinebud` (
  `login` int(2) DEFAULT NULL,
  `userid` int(11) DEFAULT NULL,
  `username` varchar(100) DEFAULT NULL,
  `usertime` varchar(50) DEFAULT NULL,
  `send` int(100) DEFAULT NULL,
  `recieve` int(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Table structure for table `registration`
--

CREATE TABLE `registration` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `confirmcode` varchar(200) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `ip` varchar(50) DEFAULT NULL,
  `verify` int(2) DEFAULT NULL,
  `enterinfo` int(2) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;


 

Advertisement

2 thoughts on “Online Chat Application in java Netbeans

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s