Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Chat Program Help

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Chat Program Help

    I have some homework I need to finish but don't know how to do a part of it. Basically its a chat program that allows you to draw pictures to each other while you're chatting. I have everything working except I need to add a list for screen names and I need the screen names to show who typed what. Hopefully someone on here can help. Here is the code so far (5 different files but they work together). There is a server too.

    Project:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
     
    public class Project extends JFrame implements ActionListener{
     
    	JTextField tf;
    	JTextArea ta;
    	JScrollPane jsp;
    	JButton connect, close;	
    	Object in, out;
    	DataObject din, dout;
    	Socket s;
    	ObjectOutputStream oos;
    	ObjectInputStream ois;
    	Listener l;
     
    	DrawPanel dp;
    	JPanel cp; //chat panel
    	JPanel np; //name panel
     
    	public Project(){
     
    		setSize(500,400);
    		setTitle("My Chat Program (Alpha)");
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    		tf = new JTextField();
    		tf.addActionListener(this);
    		ta = new JTextArea();
    		jsp = new JScrollPane(ta);
     
    		connect = new JButton("Connect");
    		connect.addActionListener(this);
    		close = new JButton("Close");
    		close.addActionListener(this);
     
    		JPanel buttonpanel = new JPanel();
    		buttonpanel.add(connect);
    		buttonpanel.add(close);
     
    		dp = new DrawPanel(this);
     
    		cp = new JPanel();
    		cp.setLayout(new BorderLayout());
    		cp.add(tf,BorderLayout.NORTH);
    		cp.add(jsp, BorderLayout.CENTER);
     
    		np = new JPanel();
    		np.setLayout(new BorderLayout());
    		np.add(tf,BorderLayout.NORTH);
    		np.add(jsp, BorderLayout.CENTER);
     
    		JPanel wrapper = new JPanel();
    		wrapper.setLayout(new GridLayout(1,0));
    		wrapper.add(cp);
    		wrapper.add(dp);
    		wrapper.add(np);
     
    		getContentPane().add(wrapper, BorderLayout.CENTER);
    		getContentPane().add(buttonpanel, BorderLayout.SOUTH);
     
     
    		setVisible(true);
    	}
     
    	public void actionPerformed(ActionEvent ae){
    		Object obj = ae.getSource();
     
    		if(obj == connect){
    			try{
    				s = new Socket("localhost", 8189);
    				oos = new ObjectOutputStream(s.getOutputStream());
     
    				dout = new DataObject();
    				l = new Listener(s);
    				l.start();
    				connect.setEnabled(false);
     
    			}catch(Exception e){
     
    				System.out.println(e.getMessage());
    			}
    		}else{
    			String temp = tf.getText();
    			tf.setText("");
    			dout.setMessage(temp);
    			try{	
    				oos.writeObject(dout);
    				oos.reset();
    			}catch(Exception e){
     
    				System.out.println(e.getMessage());
    			}
    			//ta.append(temp + "\n");
    		}
    	}
     
    	class Listener extends Thread{
     
    		Socket s;
     
    		public Listener(Socket s){
    			this.s = s;
    		}
    		public void run(){
    		   try{
    		       ois = new ObjectInputStream(s.getInputStream());
     
    		       while(true){
    		          in = ois.readObject();
     
    			  if(in instanceof DataObject){
    			     din = (DataObject)in;
    			     String text = din.getMessage() + "\n";
    			     ta.append(text);
    			     SwingUtilities.invokeLater(new Runnable() {
            		          public void run() {
                  			      ta.setCaretPosition(ta.getText().length());
            			  }
          			     });
     
    			   }else if(in instanceof LineObject){
     
    				LineObject lo = (LineObject)in;
    				dp.backg.drawLine(lo.getStartX(), lo.getStartY(), 
    					lo.getEndX(), lo.getEndY());
    				dp.record(lo.getEndX(), lo.getEndY());
          				dp.repaint();
     
    				//grab the drawpanel
    				//draw the current line	
     
    			   }
    		      }//end while
    		   }catch(Exception e){
    			System.out.println(e.getMessage());
    		   }	
    		}
     
    	}
     
     
    	public static void main(String[] args){
     
    		new Project();
     
    	}
    }


    Server:
    import java.io.*;
    import java.net.*;
    import java.util.*;
     
    public class Server{
     
    	public static void main(String[] args) throws Exception{
    		ArrayList handlerList = new ArrayList();
    		ServerSocket ss = new ServerSocket(8189);
    		while(true){
    			Socket s = ss.accept();
    			Handler h = new Handler(s, handlerList);
    			h.start();
    			handlerList.add(h);
    		}
    	}
    }
     
    class Handler extends Thread{
     
    	Socket s;
    	//DataObject d;
    	Object d;	
    	ArrayList handlers;
    	ObjectInputStream ois;
    	ObjectOutputStream oos;
     
    	public Handler(Socket s, ArrayList al){
     
    		this.s = s;
    		handlers = al;
    	}
     
    	public void broadcast(Object in){
    		Iterator itr = handlers.iterator();
     
        		//use hasNext() and next() methods to iterate through the elements
        		//System.out.println("Iterating through ArrayList elements...");
        		while(itr.hasNext()){
          			Handler current = (Handler)itr.next();
    			current.writeObject(in);
     
    		}
     
    	}
    	public void writeObject(Object d){
    		try{
    			oos.writeObject(d);
    			oos.reset();
    		}catch(Exception e){
    			System.out.println(e.getMessage());
    		}
    	}
     
    	public void run(){
    		try{
    			ois = new ObjectInputStream(s.getInputStream());
    			oos = new ObjectOutputStream(s.getOutputStream());
    			while(true){
    				d = ois.readObject();
    				if(d == null){
    					break;
    				}	
    				//System.out.println(d.getMessage());
     
    				//d.setMessage("This is the changed message.");
    				//System.out.println(d.getMessage());		
     
    				broadcast(d);
    				//oos.writeObject(d);
    				//oos.reset();
    			}
     
     
    			ois.close();
    			oos.close();
    			s.close();
    		}catch(IOException ioe){
    			System.out.println(ioe.getMessage());
    		}catch(ClassNotFoundException cnfe){
    			System.out.println("Class DataObject not found.");
    		}
    	}
    }
    /*
    ArrayList arrayList = new ArrayList();
     
        //Add elements to Arraylist
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
        arrayList.add("4");
        arrayList.add("5");
     
        Iterator itr = arrayList.iterator();
     
        while(itr.hasNext())
          System.out.println(itr.next());
    */


    Data Object:
    (For Server and Project)
    import java.io.*;
     
    public class DataObject implements Serializable{
     
    	String message;
     
    	public DataObject(){}
     
    	public void setMessage(String m){
     
    		message = m;
    	}
    	public String getMessage(){
     
    		return message;
    	}
    }

    DrawPanel:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class DrawPanel extends Panel
    	implements MouseListener, MouseMotionListener {
     
    	int lastx, lasty;
       	int width, height;
       	Image backbuffer;
       	Graphics backg;
    		LineObject lo;
    		Project parent;
     
       	public DrawPanel() {
          	width = 400;
          	height = 400;
    			Dimension d = new Dimension(width, height);
          	setPreferredSize(d);	
    			addMouseListener(this);
    			addMouseMotionListener( this );
       	}
    	public DrawPanel(Project p){
    		this();
    		parent = p;
     
    	}
    	public void record(int x, int y){
    		lastx = x;
    		lasty = y;
    	}
       	public void createBackBuffer(){
     
          		backbuffer = createImage( width, height );
          		backg = backbuffer.getGraphics();
          		backg.setColor( Color.black );
          		backg.fillRect( 0, 0, width, height );
          		backg.setColor( Color.white );
       	}
     
    	public void mouseEntered( MouseEvent e ) { 
    		record(e.getX(), e.getY());
    	}
    	public void mouseExited( MouseEvent e ) { }
    	public void mousePressed( MouseEvent e ) {
    		record(e.getX(), e.getY());
    	}
    	public void mouseClicked( MouseEvent e ) { 
    		if(e.getModifiers() == InputEvent.BUTTON3_MASK){
    			backg.setColor( Color.black );
          			backg.fillRect( 0, 0, width, height );
          			backg.setColor( Color.white );
    			repaint();
    		}
    	}
    	public void mouseReleased( MouseEvent e ) { }
     
     
     
       	public void mouseMoved( MouseEvent e ) { }
       	public void mouseDragged( MouseEvent e ) {
          		int x = e.getX();
          		int y = e.getY();
     
    		lo = new LineObject(lastx, lasty, x, y);
     
    		//backg.drawLine(lo.getStartX(), lo.getStartY(), 
    		//			lo.getEndX(), lo.getEndY());
     
     
    		//record(x, y);
          		//repaint();
          		//e.consume();
     
    		try{	
    			parent.oos.writeObject(lo);
    			parent.oos.reset();
    		}catch(Exception ex){
    			System.out.println(ex.getMessage());
    		}
       	}
     
       	public void update( Graphics g ) {
    		if(backg == null){	
    			createBackBuffer();
    		}
          		g.drawImage( backbuffer, 0, 0, this );
       	}
     
       	public void paint( Graphics g ) {
          		update( g );
       	}
     
    	public static void main(String[] args){
    		DrawPanel dp = new DrawPanel();	
    		dp.setSize(400,400);
     
    		Frame f = new Frame();
    		f.setSize(400,400);
    		f.setTitle("Drawing");
    		f.addWindowListener(new WindowAdapter(){
    			public void windowClosing(WindowEvent we){
     
    				System.exit(0);
    			}
    		});
     
    		f.add(dp, BorderLayout.CENTER);
    		f.pack();
    		f.setVisible(true);
    	}
    }

    Line Object:
    (For Draw Panel and Project)
    import java.io.*;
     
    public class LineObject implements Serializable{
     
    	int startx, starty, endx, endy;
     
    	public LineObject(int sx, int sy, int ex, int ey){ 
     
    		startx = sx;
    		starty = sy;
    		endx = ex;
    		endy = ey;
    	}
    	public void setLine(int sx, int sy, int ex, int ey){ 
     
    		startx = sx;
    		starty = sy;
    		endx = ex;
    		endy = ey;
    	}
     
    	public int getStartX(){
    		return startx;
    	}
    	public int getStartY(){
    		return starty;
    	}
    	public int getEndX(){
    		return endx;
    	}
    	public int getEndY(){
    		return endy;
    	}
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Chat Program Help

    Cross posted at Chat Program Help
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. cam and mic chat app
    By dave11791 in forum Java Networking
    Replies: 5
    Last Post: March 31st, 2013, 12:56 PM
  2. Very simple chat program hanging
    By taghack in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 3rd, 2011, 10:37 PM
  3. Simple client-server chat program
    By Saloni Patil in forum Java Networking
    Replies: 3
    Last Post: October 22nd, 2011, 09:29 AM
  4. Java LAN Chat Program
    By nevilltron in forum Java Theory & Questions
    Replies: 1
    Last Post: February 11th, 2010, 03:15 AM
  5. SSL Chat implementation
    By Koren3 in forum Java Networking
    Replies: 6
    Last Post: April 24th, 2009, 08:20 AM