Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Java programming regarding GUI based

Posted on 2001-07-28
3
238 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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
servlet web applications   metadata-complete="true" or false 3 126
hibernate jars 4 45
JavaFX TableView not displaying correctly 3 58
java example issue 5 25
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

829 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