Creating a Group Chat Window


The GroupChat.java file creates the Group Chat window of the chat room selected by an end user to send messages to all end users in the chat room. Listing 3-6 shows the contents of the GroupChat.java file:

Listing 3-6: The GroupChat.java File

start example
 /*Import required swing package classes*/ import javax.swing.event.*; import javax.swing.text.*; import javax.swing.*; /*Import required awt package classes*/ import java.awt.*; import java.awt.event.*; /*Import required util package classes*/ import java.util.*; public class  GroupChat extends JFrame implements ActionListener, KeyListener {    /*Declare object of Container class.*/    Container cont = null;    /*Declare object of JMenuBar class.*/    JMenuBar jb=new JMenuBar();    JMenu menu=new JMenu("File");    /*Declare object of JMenuItem class.*/    JMenuItem menuItem1=new JMenuItem("Got To Chat Room");    JMenuItem menuItem2=new JMenuItem("Create New Chat Room");    /*Declare object of JPanel class.*/    JPanel jp=new JPanel(new BorderLayout());    /*Declare object of JButton class.*/    JButton button=new JButton("Send");    JButton colorb=new JButton("Text Color");    /*Declare object of JTextField class.*/    JTextField text=new JTextField();    JList list;    JColorChooser chooser=new JColorChooser();    JDialog dialog;    private DefaultListModel listModel;    JTextPane je=new JTextPane();    HashMap hashmap;    /*Declare object of JScrollPane class.*/    JScrollPane scrollPane3 = new JScrollPane(text);    JScrollPane scrollPane1 = new JScrollPane(je);    JScrollPane scrollPane;    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);    /*Declare the string variable*/    String chatText=null;    String roomname;    String nickname;    String servername;    String leftmessage="";    String username="";    /*Declare object of Document class.*/    Document contentmodel;    /*Declare object of MutableAttributeSet class.*/    MutableAttributeSet nicknameattrib;    /*Function to clear the text from textpane*/    public void clearPane()    {       je.setText("");    }    /* Constructor for class*/    public GroupChat(String proomname,String pnickname,String pservername)    {       /*set the window title*/       super(" Chat Room Application: "+proomname);       cont = getContentPane();       je.setEditable(false);       nicknameattrib=new SimpleAttributeSet();       /*set the attribute for text*/       StyleConstants.setFontFamily(nicknameattrib,"Verdana");       StyleConstants.setForeground(nicknameattrib,Color.black);       contentmodel=je.getDocument();       roomname=proomname;       nickname=pnickname;       servername=pservername;       hashmap=new HashMap();       listModel=new DefaultListModel();       list=new JList(listModel);       scrollPane= new JScrollPane(list);       list.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);       list.setVisibleRowCount(5);       jb.add(menu);       menu.add(menuItem1);       menu.add(menuItem2);       Dimension minimumSize = new Dimension(300, 150);       splitPane.setTopComponent(scrollPane1);       splitPane.setBottomComponent(scrollPane);       splitPane.setDividerLocation(400);        splitPane.setPreferredSize(new Dimension(700, 200));       list.setSelectionBackground(Color.cyan);       Dimension d=button.getPreferredSize();       button.setPreferredSize(new Dimension(130, 20));       colorb.setPreferredSize(new Dimension(130, 20));       text.setPreferredSize(new Dimension(400, 20));       jp.add(text, BorderLayout.WEST);       jp.add(button, BorderLayout.EAST);       cont.add(jp, BorderLayout.SOUTH);       cont.add(splitPane, BorderLayout.CENTER);       setBounds(5, 5, 550, 550);       getRootPane().show();       menuItem1.addActionListener(this);       menuItem2.addActionListener(this);       button.addActionListener(this);       button.addKeyListener(this);       text.addKeyListener(this);       colorb.addActionListener(this);       this.addWindowListener(windowListener);       this.show();    }    /*    Function to write the message in to the text pane    */    public void writeintotextfield(String writeintotextfield, MutableAttributeSet psendernameattrib)    {       try       {          contentmodel.insertString(contentmodel.getLength(),writeintotextfield,psendernameattrib);       }       catch(Exception e)       {       }    }    /*Inner class to handle window event*/    WindowListener windowListener = new WindowAdapter()    {       public void windowClosing (WindowEvent w)       {          leftmessage="<presence type=\"unavailable\" from=\""+username+"@"+servername+"/Home\"          to=\""+roomname+"@conference."+servername+"/"+nickname+"\"></presence>";          SocketOpener.sendXMLToJabber(leftmessage);          listModel.clear();          clearPane();          setVisible(false);       }        public void windowOpened(WindowEvent e)        {          leftmessage="<presence type=\"available\" from=\""+username+"@"+servername+"/Home\"          to=\""+roomname+"@conference."+servername+"/"+nickname+"\"></presence>";          SocketOpener.sendXMLToJabber(leftmessage);          setVisible(true);       }     };    /*Function to handle key event*/    public void keyPressed(KeyEvent e)     {       if(e.getKeyCode()==KeyEvent.VK_ENTER)       {          String sendxmlstring="";          chatText=text.getText();          if (chatText.trim().equals(""))          {          }          else          {             sendxmlstring="<message to=\""+roomname+"@conference."+servername+"\"             from=\""+username+"@conference.localhost/Home\" type=\"groupchat\">";             sendxmlstring=sendxmlstring+"<body>"+chatText+"</body></message>";             SocketOpener.sendXMLToJabber(sendxmlstring);          }          text.setText("");          }       }       /*Function to handle key event*/       public void keyTyped(KeyEvent e)        {       }       /*Function to handle key event*/       public void keyReleased(KeyEvent e)        {       }       /* Function to handle  event*/       public void actionPerformed(ActionEvent e)       {          boolean modal = false;          if(e.getSource()==button)          {             String sendxmlstring="";             chatText=text.getText();             if (chatText.trim().equals(""))             {             }             else             {                sendxmlstring="<message to=\""+roomname+"@conference."+servername+"\"                from=\""+username+"@conference.localhost/Home\" type=\"groupchat\">";                sendxmlstring=sendxmlstring+"<body>"+chatText+"</body></message>";                SocketOpener.sendXMLToJabber(sendxmlstring);             }             text.setText("");          }          if(e.getSource()==menuItem2)          {             String dialog=JOptionPane.showInputDialog(this, "Please Insert the New Room Name.");             return;          }       }       /*Function to add user in a list*/       public void addNewUser(String newuser)       {          int index=0;          String newusersearch="<html><body ><font color=red          face=verdana>"+newuser+"</body></html>";          String usersearch="<html><body><font color=black          face=verdana>"+newuser+"</body></html>";          if (!((listModel.contains((Object)newusersearch))||(listModel.contains((Object)usersearch))))          {             if (newuser.equals(nickname))             {                listModel.insertElementAt("<html><body ><font color=red                face=verdana>"+newuser+"</body></html>", index);             }             else             {                listModel.insertElementAt("<html><body><font color=black                face=verdana>"+newuser+"</body></html>", index);             }          }       }       /* Function to remove user from the list*/       public void removeuser(String username)       {       String rusername="<html><body><font color=black       face=verdana>"+username+"</body></html>";       if (listModel.contains((Object)rusername))       {          boolean n=listModel.removeElement((Object)rusername);       }    }    /* Function to add user in hashmap*/    public void addNewUserinHash(String nickname,String newuserid)    {       hashmap.put(nickname,newuserid);    }    /* Function to remove user in hashmap*/    public void removeUserinHash(String nickname,String newuserid)    {       hashmap.remove(nickname);    }    /* Function to set username*/    public void setUserName(String uname)    {       username=uname;    } } 
end example

Download this listing.

In the above code, the constructor of the GroupChat class takes three strings as input parameters: proomname, pnickname, and pservername. The proomname string retrieves the name of the chat room specified by an end user. The pnickname string retrieves the user name of an end user, and the pservername string retrieves the name of the Jabber server.

The methods defined in Listing 3-6 are:

  • writeintotextfield(): Writes the message text in the text area of the Group Chat window.

  • keyPressed(): Acts as a key listener and activates an appropriate method based on the key pressed by an end user.

  • actionPerformed(): Acts as an event listener and activates an appropriate method based on the action an end user performs. End users invoke this method by clicking any button on the Group Chat window.

  • clearPane(): Refreshes the text area every time an end user opens the Group Chat window of any chat room.

  • addNewUser(): Adds a new end user to the list of existing end users in a chat room.

  • removeuser(): Removes an end user from the list of existing end users.

  • setUserName(): Sets the name of the end user who is currently logged in to the Chat Room application.

The GroupChat.java file allows end users to send messages to other end users in the chat room, as shown in Figure 3-7:

click to expand: this figure shows the group chat window containing two panes. the left pane displays the text of the messages and the right pane displays the list of logged on end users.
Figure 3-7: Creating a Group Chat Window




Developing Applications Using Jabber
Developing Applications Using Jabber
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 68

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net