Solved

Java programming regarding GUI based

Posted on 2001-07-28
3
235 Views
Last Modified: 2008-02-07
Dear Sir,

I have written normal java code for server & client, how can I make it as GUI based program,
please  write the code,




THIS IS SERVER PROGRAM WHERE IAM CREATING SERVER SOCKET & ALL OTHER STUFFS:

import java.net.*;
import java.io.*;

public class Server
{
public static void main(String args[])
{
try
{
     ServerSocket ss1=new ServerSocket(4001);
     System.out.println("Server is ready ..");
     
     while(true)
     {
     Socket s1=ss1.accept();
     System.out.println("Enter data.. ");
     DataInputStream dis1=new DataInputStream(System.in);
     String data=dis1.readLine();
     OutputStream os1=s1.getOutputStream();
     DataOutputStream dos1=new DataOutputStream(os1);
     dos1.writeUTF(data);


     InputStream is1=s1.getInputStream();
     DataInputStream dis2=new DataInputStream(is1);
     String s=dis2.readUTF();
     System.out.println(s);
     }    
     }
     catch(Exception e){}
     }
     }




THIS IS CLIENT PROGRAM WHERE IAM GOING TO CONNECT TO THE SERVER & OTHER THINGS:

import java.net.*;
import java.io.*;
public class Clinet
{
public static void main(String args[])
{
try
{

InetAddress ia1=InetAddress.getByName("lab3-mn04");
while(true)
{
Socket s1=new Socket(ia1,4001);
InputStream is1=s1.getInputStream();
DataInputStream d1=new DataInputStream(is1);
String s=d1.readUTF();
System.out.println(s);

System.out.println("Enter data..");
DataInputStream d2=new DataInputStream(System.in);
String s2=d2.readLine();

OutputStream o1=s1.getOutputStream();
DataOutputStream d3=new DataOutputStream(o1);
d3.writeUTF(s2);
}
}
catch(Exception e){}
}
}
0
Comment
Question by:srini_bhat
3 Comments
 
LVL 1

Accepted Solution

by:
poluru earned 100 total points
ID: 6333022
i've wriiten one and iam giving that to u.

import java.net.Socket;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.OptionalDataException;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.border.LineBorder;
import javax.swing.JTextArea;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JButton;
import javax.swing.JToggleButton;
import javax.swing.JList;
import javax.swing.JLabel;
import javax.swing.ListCellRenderer;
import javax.swing.AbstractListModel;
import javax.swing.JOptionPane;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
import javax.swing.ImageIcon;
import javax.swing.BoxLayout;
import javax.swing.LookAndFeel;
import java.awt.Color;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.GraphicsEnvironment;
import java.awt.Component;
import java.awt.event.*;

public class ObjectClient extends JFrame implements ActionListener, Runnable
{

      public ObjectClient()
      {
            UIManager.put("ScrollBar.allowsAbsolutePositioning",new Boolean(true));
            setIconImage(new ImageIcon(System.getProperty("user.dir")+System.getProperty("file.separator")+"images/icon.gif").getImage());
            txtChat = new TextPane();
            txtChat.setEditable(false);
            txtChat.setLayout(new BoxLayout(txtChat,BoxLayout.Y_AXIS));

            JScrollPane scroller = new JScrollPane();
            scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
            scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
            scroller.getViewport().add(txtChat);

            txtMsg = new JTextArea(2,40);
            txtMsg.setLineWrap(true);


            UIManager.put("OptionPane.okButtonText","Login");

            listUsers = new JList(listarr);
            listUsers.setCellRenderer(new MyCellRenderer());
            listUsers.setForeground(Color.red);
            listUsers.setModel(new GeneratedListModel(this));
            listUsers.addMouseListener(new ListListener(this));

            JScrollPane scrollerList = new JScrollPane();
            scrollerList.getViewport().add(listUsers);
            scrollerList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );

            listRooms = new JList(listarrrooms);
            listUsers.setForeground(Color.red);

            JScrollPane scrollerListRooms = new JScrollPane();
            scrollerListRooms.getViewport().add(listUsers);
            scrollerListRooms.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );

            JSplitPane split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,scrollerList,scrollerListRooms);
            split.setOneTouchExpandable(true);




            bsend = new JButton("Send");

            pMain = new JPanel(new BorderLayout());
            pBottom = new JPanel();
            txtMsg.setLayout(new FlowLayout(FlowLayout.RIGHT));
            colorBtn=new JButton("FontColor");

            GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
            fontNames=ge.getAvailableFontFamilyNames();
            jcb=new JComboBox(fontNames);

            jcb.addActionListener(this);

            JPanel northPnl=new JPanel();
            northPnl.setLayout(new FlowLayout());
            northPnl.add(jcb);
            northPnl.add(colorBtn);
            bold=new JToggleButton("B");
            italic=new JToggleButton("I");
            under=new JToggleButton("U");
            bold.setFont(new Font("Times New Roman",Font.BOLD,14));
            italic.setFont(new Font("Times New Roman",Font.ITALIC+Font.BOLD,14));
            under.setFont(new Font("Times New Roman",Font.BOLD+Font.ROMAN_BASELINE,14));
            bold.addActionListener(this);
            italic.addActionListener(this);
            under.addActionListener(this);

            northPnl.add(bold);
            northPnl.add(italic);
            northPnl.add(under);

            JScrollPane sendPane=new JScrollPane(txtMsg);
            pBottom.add(sendPane);
            pBottom.add(bsend);

            pMain.add(northPnl,"North");
            pMain.add(scroller,"Center");
            pMain.add(split,"East");
            pMain.add(pBottom, "South");

            getContentPane().add(pMain);
            colorBtn.addActionListener(this);
            bsend.addActionListener(this);
            addWindowListener(new WindowAdapter()
            {
                  public void windowClosing(WindowEvent w)
                  {
                        setVisible(false);
                        try
                        {
                              ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
                              m=new Message();
                              m.user=user;
                              m.doRemove=true;
                              out.writeObject(m);
                              out.flush();
                        }
                        catch(Exception ee)
                        {
                              System.out.println("Exception:in windowclosing()"+ee);
                        }
                        dispose();
                        System.exit(0);
                  }
            });


            try
            {
                  // Look and Fell setting to Motiff
                  UIManager.setLookAndFeel((LookAndFeel)Class.forName("com.sun.java.swing.plaf.motif.MotifLookAndFeel").newInstance());//javax.swing.plaf.metal.MetalLookAndFeel
                  SwingUtilities.updateComponentTreeUI(this);
            }
            catch(Exception e)
            {
                  System.out.println("setting looknfeel : Motiff not supported"+e.getMessage());
            }
            int i=123;
            String message="Please Type In The UserName : ";
       loop:      do
             {
                  user=JOptionPane.showInputDialog(this,message,"Login",JOptionPane.INFORMATION_MESSAGE);
                  setBounds(100,100,600,330);
                  if(user!=null && !user.trim().equals(""))
                  {
                        int cflag=connect(user+"####makeconnection#### : entered the room");
                        System.out.println("connectFlag:"+cflag);
                        if(cflag==0)
                        {
                              JOptionPane.showMessageDialog(this,"LoginFailed!!!                                       ");
                              System.exit(0);
                        }
                        else
                        {
                              showStatus();
                              setTitle("B2B Chat Room : "+user);
                              break loop;
                        }
                  }
                  else if(user!=null && user.trim().equals(""))
                  {
                        System.out.println("in equals(\"\"):");
                        message="UserName should not be null, Enter the UseName : ";
                        continue loop;
                  }
                  else
                  {
                        System.out.println("in else:");
                        i=JOptionPane.showConfirmDialog(this,"Do you really want to exit the application ? ");
                        message="Please Type in the UserName : ";
                        if(i==JOptionPane.YES_OPTION)
                        {
                              System.exit(0);
                        }
                  }
            }
            while(i==JOptionPane.NO_OPTION || i==JOptionPane.CANCEL_OPTION);
            int flag=1;
            while(flag<=100)
            {
                  jpb.setValue(flag);
                  flag+=5;
                  try
                  {
                        Thread.sleep(750);
                  }
                  catch(Exception e)
                  {

                  }
            };
      }

      private void showStatus()
      {
            jf=new JFrame("Login Status");
            jf.getContentPane().setLayout(new GridLayout(3,1));
            jf.getContentPane().add(new JLabel("Login progress, please wait...."));
            UIManager.put("ProgressBar.foreground",Color.blue);
            jpb=new JProgressBar(0,0,100);
            jpb.setBorderPainted(true);
            jf.getContentPane().add(jpb);
            jf.setBounds(200,200,260,90);
            jf.setResizable(false);
            jf.setVisible(true);
      }

      public static void main(String args[])
      {
            new ObjectClient();

      }

      public int connect(String msg)
      {
            try
            {
                  s=new Socket("localhost",6000);
                  m=new Message();
                  m.user=user;
                  m.msg="  entered the room";
                  m.msgColor=msgColor;
                  m.style=style;
                  m.fontfamily=ffamily;
                  ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
                  out.writeObject(m);
                  out.flush();
                  Thread tt=new Thread(this);
                  tt.start();
                  return 1;
            }
            catch(Exception ee)
            {
                  System.out.println("Exception:in connect() "+ee);
                  return 0;
            }
      }

      public void run()
      {
            try
            {
                  while(true)
                  {
                        ObjectInputStream ois=new ObjectInputStream(s.getInputStream());
                        Message mm=(Message)ois.readObject();
                        jf.dispose();
                        this.setVisible(true);
                        listarr=mm.users;
                        listUsers.setListData(listarr);
                        if(mm.isPvtMsg)
                        {
                              if(user.equals(mm.user))
                                    txtChat.append( mm.msg+mm.pvtUsr , 14 , mm.msgColor , mm.fontfamily , mm.style );
                              else
                                    txtChat.append(mm.msg,14,mm.msgColor,mm.fontfamily,mm.style);
                        }
                        else
                        {
                              txtChat.append(mm.user+" : "+mm.msg,14,mm.msgColor,mm.fontfamily,mm.style);
                        }
                        txtMsg.setText("");
                        txtMsg.requestFocus();

                  }
            }
            catch(OptionalDataException ode)
            {
                  System.out.println(ode.getMessage());
            }
            catch(Exception io)
            {
                        System.out.println(io.getMessage());
            }
      }

      public void actionPerformed(ActionEvent ae)
      {
            if(ae.getSource()==colorBtn)
            {
                  Color temp=JColorChooser.showDialog(this,"Choose your font color",msgColor);
                  if(temp!=null)
                  {
                        msgColor=temp;
                        colorBtn.setForeground(msgColor);
                  }

            }
            else if(ae.getSource()==jcb)
            {
                  ffamily=(String)jcb.getSelectedItem();
                  Font msgFont= new Font(ffamily, style, 14);
                  txtMsg.setFont(msgFont);
            }
            else if(ae.getSource()==bold || ae.getSource()==italic)
            {
                  boolean bsel=bold.isSelected(),isel=italic.isSelected();
                  if(bsel && isel)
                        style=Font.BOLD+Font.ITALIC;
                  else if(bsel)
                        style=Font.BOLD;
                  else if(isel)
                        style=Font.ITALIC;
                  else
                        style=Font.PLAIN;

                        Font msgFont=new Font(ffamily,style,14);
                        txtMsg.setFont(msgFont);

            }
            else if(ae.getSource()==bsend)
            {
                  String msg=txtMsg.getText();
                  sendToServer(msg,false,null);
            }
      }

      private void sendToServer(String msg,boolean pvt,String pvtUsr)
      {
            if(msg.trim().equals("")) return;
            else
            {
                  try
                  {
                        Message m=new Message();
                        m.user=user;
                        m.msg=msg;
                        if(pvt)
                        {
                              m.isPvtMsg=true;
                              m.pvtUsr=pvtUsr;
                        }
                        m.msgColor=this.msgColor;
                        m.style=style;
                        m.fontfamily=ffamily;
                        ObjectOutputStream out=new ObjectOutputStream(s.getOutputStream());
                        out.writeObject(m);
                        out.flush();
                  }
                  catch(Exception e)
                  {
                        System.out.println("Exception while sending msg "+e.getMessage());
                  }
            }

      }






      class MyCellRenderer extends JLabel implements ListCellRenderer
            {
                ImageIcon longIcon = new ImageIcon(getClass().getResource("/red.gif"));

                        public MyCellRenderer() {
                            setOpaque(true);
                        }
                        public Component getListCellRendererComponent(
                            JList list,
                            Object value,
                            int index,
                            boolean isSelected,
                            boolean cellHasFocus)
                        {
                            setText(value.toString());
                            setIcon(longIcon);
                            setBackground(isSelected ? new Color(153,153,204) : list.getBackground());
                            setForeground(isSelected ? Color.white : Color.black);
                            setBorder(isSelected ? new LineBorder(Color.black,2) : null);
                            return this;
                             }
             }

      class GeneratedListModel extends AbstractListModel
      {
             ObjectClient demo;

             public Vector prefix;

             public GeneratedListModel (ObjectClient demo)
             {
                 this.demo = demo;
                 prefix=demo.listarr;
             }

             public Object getElementAt(int index)
             {

                return prefix.get(index);
             }
             public int getSize()
             {
                       return listarr.size();
             }
      }
      class ListListener extends MouseAdapter
      {
            public void mouseClicked(java.awt.event.MouseEvent me)
            {
                  String pvtUser=(String)listUsers.getSelectedValue();
                  UIManager.put("OptionPane.okButtonText","Send");
                  String pvtMsg=JOptionPane.showInputDialog(parent,"Please type in the private message :","PVTMessage to "+pvtUser,JOptionPane.INFORMATION_MESSAGE);

                  sendToServer(pvtMsg,true,pvtUser);
            }
            public ListListener(ObjectClient cl)
            {
                  parent=cl;
            }
            ObjectClient parent;
      }

      private static Hashtable h=new Hashtable();
      private Socket s;

      TextPane txtChat;
      JTextArea txtMsg;
      JList listUsers,listRooms;
      JButton bsend,colorBtn;
      JToggleButton bold,italic,under;

      JPanel pMain;
      JPanel pBottom;

      JOptionPane dialog;
      String user="";
      String msg;
      private Vector listarr=new Vector();
      private Vector listarrrooms=new Vector();

      JFrame jf;
      JProgressBar jpb;
      JComboBox jcb;
      String[] fontNames;
      Color msgColor=Color.darkGray;
      String ffamily="Comic Sans MS";
      int style=0;
      Message m;

}

Iam using one helper calss Message.java and ObjectServer.java (Server Program).
i can give u if u want.
0
 

Expert Comment

by:CleanupPing
ID: 9061932
srini_bhat:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 9208350
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


[points to poluru]


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This video teaches viewers about errors in exception handling.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now