Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Chat Program Help

setpreferredsize

  • Please log in to reply
3 replies to this topic

#1 WooZy

WooZy

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 29 April 2012 - 08:28 PM

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;
    }
}

  • 0

#2 Norm

Norm

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 397 posts
  • Location:Eastern Florida
  • Programming Language:Java, C++, Assembly

Posted 30 April 2012 - 06:21 AM

Cross posted at http://www.javaprogr....html#post64989
  • 0

#3 WooZy

WooZy

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts

Posted 30 April 2012 - 07:19 AM

Cross posted at http://www.javaprogr....html#post64989


Thanks for the help man, I really appreciate it...
  • 0

#4 Norm

Norm

    CC Addict

  • Senior Member
  • PipPipPipPipPip
  • 397 posts
  • Location:Eastern Florida
  • Programming Language:Java, C++, Assembly

Posted 30 April 2012 - 07:21 AM

That wasn't for you. It was for the other volunteers so they can see if the question has already been answered and not waste time.
  • 1





Also tagged with one or more of these keywords: setpreferredsize

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download