+ All Categories
Home > Software > Chat Room System using Java Swing

Chat Room System using Java Swing

Date post: 12-Jul-2015
Category:
Upload: tejas-garodia
View: 1,051 times
Download: 1 times
Share this document with a friend
26
1 | Page Project on Online Chat Room System Name: Tejas Omprakash Agarwal ID: 312-66-450 Class: CS 602 Semester: Fall 2014 Date: Dec 15th, 2014 URL: http://web.njit.edu/~toa9/chatroom/ Email: [email protected] Extras: - Project is built in Swing - Onhover, OnActive color change on Panel, Buttons, Radio Button Project Description: My project is an online Chat Room System which is built in Java Swing. The system adopts 3 tier architecture in which the client request server to register itself to the room, server register’s the user to the room and finally the client can share content with other registered client via server. The system allows the user to connect from different location in a common chat-room where they can broadcast text messages and share drawing with other registered users. Features: Apart from sharing content, the server broadcast entry and exist of the user. The chat window of every user is registered with client specific Title. Messages from client are prepend with their name. Cosmetic color change is implemented on-hover, on-active on the chat window, its borders and buttons. System allows tracking the user who is currently present in the chat room. System has the feature to save text messages/history in a text file from the chat window to the client local system.
Transcript
Page 1: Chat Room System using Java Swing

1 | P a g e

Project on

Online Chat Room System

Name: Tejas Omprakash Agarwal

ID: 312-66-450

Class: CS 602

Semester: Fall 2014

Date: Dec 15th, 2014

URL: http://web.njit.edu/~toa9/chatroom/

Email: [email protected]

Extras:

- Project is built in Swing

- Onhover, OnActive color change on Panel, Buttons, Radio Button

Project Description:

My project is an online Chat Room System which is built in Java Swing. The system adopts

3 tier architecture in which the client request server to register itself to the room, server

register’s the user to the room and finally the client can share content with other registered

client via server. The system allows the user to connect from different location in a common

chat-room where they can broadcast text messages and share drawing with other registered

users.

Features:

Apart from sharing content, the server broadcast entry and exist of the user.

The chat window of every user is registered with client specific Title.

Messages from client are prepend with their name.

Cosmetic color change is implemented on-hover, on-active on the chat window, its

borders and buttons.

System allows tracking the user who is currently present in the chat room.

System has the feature to save text messages/history in a text file from the chat

window to the client local system.

Page 2: Chat Room System using Java Swing

2 | P a g e

Usage Instruction:

Server Activation

Open SSH Secure Shell

Locate the server.java file in the current directory

Compile the server.java file using command “javac server.java”

Activate server using command “java server”

Server activated and ready to listen

Client Activation

Locate login.java and client.java file at client local system

Compile the login.java and client.java file using command “javac login.java” and

“javac client.java”

Activate client using command “java login”

Register client by entering name in the text field as shown in figure 1

On successful registration chat room window with Title as registered name will pop-

up as shown in figure 3 along with broadcast message “ClientName: Has Entered”

Client can type the message using the bottom text-field and can broadcast message by

clicking on Send button

Client can draw on Drawing Board and share it with other active clients

Page 3: Chat Room System using Java Swing

3 | P a g e

Filename: server.java

import java.io.*;

import java.net.*;

import java.util.*;

import javax.swing.JOptionPane;

public class server {

public static void main(String[] args) throws IOException {

ArrayList<Handler> handlers = new ArrayList<Handler>();

try {

ServerSocket socket = new ServerSocket(4543);

while (true) {

Socket incoming = socket.accept();

new Handler(incoming, handlers).start();

}

} catch (IOException e) {

JOptionPane.showMessageDialog(null, "Connectio problem is here" +

e.getMessage());

}

}

}

class Handler extends Thread {

Object myObject = null;

private Socket incoming;

ArrayList<Handler> handlers;

ObjectInputStream ois;

ObjectOutputStream oos;

public Handler(Socket incoming, ArrayList<Handler> handlers) {

this.incoming = incoming;

this.handlers = handlers;

handlers.add(this);

}

public synchronized void broadcast(DataObjectChild obj) {

Iterator<Handler> it = handlers.iterator();

while (it.hasNext()) {

Handler current = it.next();

try {

current.oos.writeObject(obj);

current.oos.reset();

} catch (IOException ex) {

System.out.println(ex.getMessage());

}

}

}

Page 4: Chat Room System using Java Swing

4 | P a g e

public synchronized void broadcast(LineMessage obj) {

Iterator<Handler> it = handlers.iterator();

while (it.hasNext()) {

Handler current = it.next();

try {

current.oos.writeObject(obj);

current.oos.reset();

} catch (IOException ex) {

System.out.println(ex.getMessage());

}

}

}

@Override

public void run() {

try {

ois = new ObjectInputStream(incoming.getInputStream());

oos = new ObjectOutputStream(incoming.getOutputStream());

} catch (IOException e) {

System.out.println("Problem constructing streams" + e.getMessage());

}

boolean done = false;

while (!done) {

try {

myObject = ois.readObject();

if (myObject instanceof DataObjectChild) {

System.out.println("Reading message from dobject : " + myObject);

System.out.println("Message received before broadcast" + myObject.toString());

broadcast((DataObjectChild) myObject);

} else if (myObject instanceof LineMessage) {

broadcast((LineMessage) myObject);

}

} catch (IOException e) {

System.out.println(e);

e.printStackTrace();

done = true;

} catch (ClassNotFoundException e) {

System.out.println("Can't find DataObject!!");

}

}

}

}

Page 5: Chat Room System using Java Swing

5 | P a g e

Filename: login.java

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.net.Socket;

public class login extends javax.swing.JFrame {

Socket socket = null;

static String stringname;

ObjectOutputStream oos;

ObjectInputStream ois;

/**

* Creates new form login

*/

public login() {

initComponents();

}

/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jPanel1 = new javax.swing.JPanel();

name = new javax.swing.JTextField();

jButton1 = new javax.swing.JButton();

jLabel1 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setTitle("Register User");

name.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

nameActionPerformed(evt);

}

});

jButton1.setText("Submit");

jButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton1ActionPerformed(evt);

}

});

Page 6: Chat Room System using Java Swing

6 | P a g e

jLabel1.setText("Please Enter your name:");

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

jPanel1.setLayout(jPanel1Layout);

jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

jPanel1Layout.createSequentialGroup()

.addGap(34, 34, 34)

.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 155,

Short.MAX_VALUE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI

NG)

.addComponent(jButton1)

.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 148,

javax.swing.GroupLayout.PREFERRED_SIZE))

.addGap(53, 53, 53))

);

jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(23, 23, 23)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASEL

INE)

.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

.addGap(18, 18, 18)

.addComponent(jButton1)

.addContainerGap(19, Short.MAX_VALUE))

);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

);

Page 7: Chat Room System using Java Swing

7 | P a g e

pack();

}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

stringname = name.getText();

System.out.println("Name is: " + stringname);

client c = new client();

c.setTitle(stringname);

login aa = new login();

c.setVisible(true);

}

private void nameActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and

feel.

* For details see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

try {

for (javax.swing.UIManager.LookAndFeelInfo info :

javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

}

}

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

Page 8: Chat Room System using Java Swing

8 | P a g e

java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

}

//</editor-fold>

/* Create and display the form */

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new login().setVisible(true);

}

});

}

// Variables declaration - do not modify

private javax.swing.JButton jButton1;

private javax.swing.JLabel jLabel1;

private javax.swing.JPanel jPanel1;

private javax.swing.JTextField name;

// End of variables declaration

}

Page 9: Chat Room System using Java Swing

9 | P a g e

Filename: DataObject.java

import java.io.Serializable;

public class DataObject implements Serializable {

private String message;

public DataObject() {

}

public DataObject(String message) {

setMessage(message);

}

public void setMessage(String message) {

this.message = message;

}

public String getMessage() {

return message;

}

}

class DataObjectChild extends DataObject {

private String name;

private String image;

public void setName(String s) {

name = s;

}

public String getName() {

return name;

}

public String getImage() {

return image;

}

public void setImage(String image) {

this.image = image;

}

}

Page 10: Chat Room System using Java Swing

10 | P a g e

Filename: client.java

import java.awt.Component;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.net.Socket;

import java.util.ArrayList;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.imageio.ImageIO;

import javax.swing.JOptionPane;

public class client extends javax.swing.JFrame implements Runnable {

/**

* Creates new form client

*/

Socket socket = null;

ObjectOutputStream oos;

ObjectInputStream ois;

String name;

DataObjectChild dobject;

login lo = new login();

private Thread t;

protected int lastX = 0, lastY = 0;

ArrayList<Line> linelist;

public client() {

try {

socket = new Socket("afsaccess1.njit.edu", 4543);

oos = new ObjectOutputStream(socket.getOutputStream());

ois = new ObjectInputStream(socket.getInputStream());

JOptionPane.showMessageDialog(null, "Connected to server");

DataObjectChild tempObject = new DataObjectChild();

tempObject.setName(login.stringname);

tempObject.setMessage("Has Entered.");

oos.writeObject(tempObject);

} catch (IOException ex) {

System.out.println("Exception before thread creation :" + ex.getMessage());

}

Thread thread = new Thread(this, login.stringname);

thread.start();

}

public static BufferedImage getScreenShot(Component component) {

Page 11: Chat Room System using Java Swing

11 | P a g e

BufferedImage image = new BufferedImage(component.getWidth(),

component.getHeight(), BufferedImage.TYPE_INT_RGB);

component.paint(image.getGraphics());

return image;

}

public static void SaveScreenShot(Component component, String filename) throws

Exception {

BufferedImage img = getScreenShot(component);

ImageIO.write(img, "png", new File(filename));

}

/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

txt_msg = new javax.swing.JTextField();

client_button_send = new javax.swing.JButton();

jScrollPane1 = new javax.swing.JScrollPane();

client_txt_recmsg = new javax.swing.JTextArea();

jLabel1 = new javax.swing.JLabel();

jButton2 = new javax.swing.JButton();

jRadioButton1 = new javax.swing.JRadioButton();

game22 = new Game2();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

setResizable(false);

addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent evt) {

formWindowClosing(evt);

}

});

txt_msg.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

txt_msgActionPerformed(evt);

}

});

client_button_send.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N

client_button_send.setText("Send");

client_button_send.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

client_button_sendActionPerformed(evt);

}

Page 12: Chat Room System using Java Swing

12 | P a g e

});

client_txt_recmsg.setEditable(false);

client_txt_recmsg.setColumns(20);

client_txt_recmsg.setRows(5);

jScrollPane1.setViewportView(client_txt_recmsg);

jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N

jLabel1.setText("Drawing Board");

jButton2.setText("Send Drawing");

jButton2.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jButton2ActionPerformed(evt);

}

});

jRadioButton1.setText("Record Chat");

jRadioButton1.addChangeListener(new javax.swing.event.ChangeListener() {

public void stateChanged(javax.swing.event.ChangeEvent evt) {

jRadioButton1StateChanged(evt);

}

});

jRadioButton1.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

jRadioButton1ActionPerformed(evt);

}

});

jRadioButton1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

public void propertyChange(java.beans.PropertyChangeEvent evt) {

jRadioButton1PropertyChange(evt);

}

});

javax.swing.GroupLayout game22Layout = new javax.swing.GroupLayout(game22);

game22.setLayout(game22Layout);

game22Layout.setHorizontalGroup(

game22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0, 185, Short.MAX_VALUE)

);

game22Layout.setVerticalGroup(

game22Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0, 321, Short.MAX_VALUE)

);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

Page 13: Chat Room System using Java Swing

13 | P a g e

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,

Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,

false)

.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 422,

Short.MAX_VALUE)

.addComponent(txt_msg))

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(client_button_send)

.addGap(18, 18, 18)

.addComponent(jButton2)

.addGap(18, 18, 18))

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(45, 45, 45)

.addComponent(jLabel1))

.addGroup(layout.createSequentialGroup()

.addGap(18, 18, 18)

.addComponent(jRadioButton1)))

.addContainerGap())))

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addContainerGap(461, Short.MAX_VALUE)

.addComponent(game22, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(20, Short.MAX_VALUE)))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addContainerGap()

.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE,

346, Short.MAX_VALUE))

.addGroup(layout.createSequentialGroup()

.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 40,

Short.MAX_VALUE)

Page 14: Chat Room System using Java Swing

14 | P a g e

.addGap(319, 319, 319)))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(txt_msg, javax.swing.GroupLayout.DEFAULT_SIZE, 52,

Short.MAX_VALUE)

.addContainerGap())

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(client_button_send)

.addComponent(jButton2))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,

javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

.addComponent(jRadioButton1))))

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

layout.createSequentialGroup()

.addContainerGap(36, Short.MAX_VALUE)

.addComponent(game22, javax.swing.GroupLayout.PREFERRED_SIZE,

javax.swing.GroupLayout.DEFAULT_SIZE,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(74, Short.MAX_VALUE)))

);

pack();

}// </editor-fold>

private void txt_msgActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

}

private void client_button_sendActionPerformed(java.awt.event.ActionEvent evt) {

try {

//ta.append(t.getText());

dobject = new DataObjectChild();

dobject.setMessage(txt_msg.getText().trim());

dobject.setName(login.stringname);

if (dobject.getMessage().equals("bye")) {

DataObjectChild tempObject = new DataObjectChild();

tempObject.setName(login.stringname);

tempObject.setMessage("Has Exited .");

oos.writeObject(tempObject);

System.exit(0);

}

oos.writeObject(dobject);

txt_msg.setText("");

Page 15: Chat Room System using Java Swing

15 | P a g e

} catch (IOException ioe) {

System.out.println("Problem sending message to server: " + ioe.getMessage());

}

}

private void formWindowClosing(java.awt.event.WindowEvent evt) {

// TODO add your handling code here:

DataObjectChild tempObject = new DataObjectChild();

tempObject.setName(login.stringname);

tempObject.setMessage("Has Exited.");

try {

oos.writeObject(tempObject);

} catch (IOException ioe) {

}

System.exit(0);

}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

try {

LineMessage lm = new LineMessage();

lm.setMessage(game22.linelist);

oos.writeObject(lm);

} catch (Exception ex) {

System.out.println("Exception is : " + ex.getMessage());

}

}

private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {

FileWriter pw = null;

try {

// TODO add your handling code here:

pw = new FileWriter("filename_" + login.stringname + ".txt");

client_txt_recmsg.write(pw);

} catch (IOException ex) {

Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);

} finally {

try {

pw.close();

} catch (IOException ex) {

Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);

}

}

}

private void jRadioButton1StateChanged(javax.swing.event.ChangeEvent evt) {

// TODO add your handling code here:

Page 16: Chat Room System using Java Swing

16 | P a g e

}

private void jRadioButton1PropertyChange(java.beans.PropertyChangeEvent evt) {

// TODO add your handling code here:

}

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

/* Set the Nimbus look and feel */

//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and

feel.

* For details see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

*/

new client().setVisible(true);

try {

for (javax.swing.UIManager.LookAndFeelInfo info :

javax.swing.UIManager.getInstalledLookAndFeels()) {

if ("Nimbus".equals(info.getName())) {

javax.swing.UIManager.setLookAndFeel(info.getClassName());

break;

}

}

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(client.class.getName()).log(java.util.logging.Level.SEVE

RE, null, ex);

}

//</editor-fold>

/* Create and display the form */

}

@Override

Page 17: Chat Room System using Java Swing

17 | P a g e

public void run() {

initComponents();

for (;;) {

try {

Object o = ois.readObject();

if (o != null) {

if (o instanceof DataObjectChild) {

DataObjectChild sm = (DataObjectChild) o;

client_txt_recmsg.append(sm.getName() + ": " + sm.getMessage() + "\n");

} else if (o instanceof LineMessage) {

LineMessage lm = (LineMessage) o;

ArrayList<Line> linelist = (ArrayList) lm.getMessage();

game22.drawit(linelist);

}

}

} catch (IOException e) {

System.out.println("IO Exception: " + e.getMessage());

} catch (ClassNotFoundException ex) {

Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);

}

}

}

// Variables declaration - do not modify

private javax.swing.JButton client_button_send;

private javax.swing.JTextArea client_txt_recmsg;

private Game2 game22;

private javax.swing.JButton jButton2;

private javax.swing.JLabel jLabel1;

private javax.swing.JRadioButton jRadioButton1;

private javax.swing.JScrollPane jScrollPane1;

private javax.swing.JTextField txt_msg;

// End of variables declaration

}

Page 18: Chat Room System using Java Swing

18 | P a g e

Filename: Game2.java

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Shape;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.logging.Level;

import java.util.logging.Logger;

import javax.swing.JFrame;

public class Game2 extends javax.swing.JPanel {

protected int lastX = 0, lastY = 0;

private Shape shape;

ArrayList<Line> linelist;

client c;

ObjectInputStream ois;

public void paint(Graphics g) {

super.paintComponent(g);

Iterator<Line> it = linelist.iterator();

while (it.hasNext()) {

Line current = it.next();

g.drawLine(current.getStartX(), current.getStartY(),

current.getEndX(), current.getEndY());

}

g.drawString("Painted on JPanel", 100, 100);

}

public static void main(String[] args) {

JFrame frame = new JFrame();

frame.setBackground(Color.WHITE);

frame.add(new Game2());

frame.setSize(300, 300);

frame.setVisible(true);

}

public void drawit(ArrayList<Line> linelist) {

this.linelist = linelist;

repaint();

}

/**

* Creates new form Game2

*/

public Game2() {

linelist = new ArrayList<Line>();

Page 19: Chat Room System using Java Swing

19 | P a g e

initComponents();

}

public Game2(client c) {

setBackground(Color.WHITE);

linelist = new ArrayList<Line>();

this.c = c;

}

/**

* This method is called from within the constructor to initialize the form.

* WARNING: Do NOT modify this code. The content of this method is always

* regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

setBackground(new java.awt.Color(255, 255, 255));

addMouseListener(new java.awt.event.MouseAdapter() {

public void mousePressed(java.awt.event.MouseEvent evt) {

formMousePressed(evt);

}

public void mouseReleased(java.awt.event.MouseEvent evt) {

formMouseReleased(evt);

}

});

addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {

public void mouseDragged(java.awt.event.MouseEvent evt) {

formMouseDragged(evt);

}

});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);

this.setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0, 170, Short.MAX_VALUE)

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0, 300, Short.MAX_VALUE)

);

}// </editor-fold>

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

// TODO add your handling code here:

lastX = evt.getX();

lastY = evt.getY();

}

Page 20: Chat Room System using Java Swing

20 | P a g e

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

// TODO add your handling code here:

int x = evt.getX();

int y = evt.getY();

getGraphics().drawLine(lastX, lastY, x, y);

}

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

// TODO add your handling code here:

int endX = evt.getX();

int endY = evt.getY();

Line line = new Line(lastX, lastY, endX, endY);

linelist.add(line);

lastX = endX;

lastY = endY;

repaint();

}

// Variables declaration - do not modify

// End of variables declaration

}

Page 21: Chat Room System using Java Swing

21 | P a g e

LineMessage.java

import java.io.Serializable;

import java.util.ArrayList;

class LineMessage implements Serializable {

ArrayList<Line> message;

public void setMessage(Object message) {

this.message = (ArrayList) message;

}

public Object getMessage() {

return message;

}

}

class Line extends DataObjectChild implements Serializable {

int startx, starty, endx, endy;

public Line() {

}

public Line(int sx, int sy, int ex, int ey) {

setStartX(sx);

setStartY(sy);

setEndX(ex);

setEndY(ey);

}

public void setStartX(int sx) {

Page 22: Chat Room System using Java Swing

22 | P a g e

startx = sx;

}

public void setStartY(int sy) {

starty = sy;

}

public void setEndX(int ex) {

endx = ex;

}

public void setEndY(int ey) {

endy = ey;

}

public int getStartX() {

return startx;

}

public int getStartY() {

return starty;

}

public int getEndX() {

return endx;

}

public int getEndY() {

return endy;

}

}

Page 23: Chat Room System using Java Swing

23 | P a g e

Figures:

Figure 1: Register User

Figure 2: Alert Message if the Client is connected to the server

Figure 3: Client1 Chat Window with Client Name: John

Page 24: Chat Room System using Java Swing

24 | P a g e

Figure 4: Broadcast message on entry of another client2 Martin on client1 John Chat Window

Figure 5: Message broadcast from client1 John chat window

Page 25: Chat Room System using Java Swing

25 | P a g e

Figure 6: Broadcast message “Hello Martin” from client1 John received on Martin Chat

Window

Figure 7: Drawing Shared between Client1 John and Client2 Martin

Page 26: Chat Room System using Java Swing

26 | P a g e

Figure 8: Onclick Record Chat radio button, Text file created with Client specific name

(Username_John) containing all text messages

Figure 9: Broadcast message “Has Exited” on client1 John on departure of Client2 Martin


Recommended