KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sellwin > gui > ChatDialog


1 package sellwin.gui;
2
3 import java.util.*;
4 import java.io.*;
5 import java.net.*;
6 import java.awt.*;
7 import java.awt.event.*;
8 import javax.swing.*;
9 import javax.swing.event.*;
10 import javax.swing.text.*;
11
12 import sellwin.utils.*;
13 import sellwin.domain.*;
14
15 // SellWin http://sourceforge.net/projects/sellwincrm
16
//Contact support@open-app.com for commercial help with SellWin
17
//This software is provided "AS IS", without a warranty of any kind.
18

19 /**
20  * chat dialog that shows the chat window, users can view
21  * what other users are online, and strike up online chats with
22  * them, a simple chat protocol is implemented
23  *
24  * @author jmccormi
25  */

26 public class ChatDialog extends javax.swing.JDialog JavaDoc implements GUIChars {
27
28     // the basic widgets that make up the screen's look
29

30     private javax.swing.JTextArea JavaDoc msgArea;
31     private javax.swing.JPanel JavaDoc buttonPanel;
32     private javax.swing.JList JavaDoc usersList;
33     private JCheckBox beepBox;
34     private javax.swing.JButton JavaDoc sendButton;
35     private javax.swing.JButton JavaDoc closeButton;
36     private javax.swing.JTextArea JavaDoc conversationArea;
37     private JTextPane conversationTextPane;
38     private javax.swing.JScrollPane JavaDoc jScrollPane3;
39     private javax.swing.JScrollPane JavaDoc jScrollPane2;
40     private javax.swing.JScrollPane JavaDoc jScrollPane1;
41     private javax.swing.JPanel JavaDoc mainPanel;
42
43     // some text styles used to display the received chat text
44
private String JavaDoc newline = "\n";
45     private String JavaDoc[] initStyles = { "bold", "regular" };
46     private Style bold, regular, regularFrom;
47   
48     // a thread that runs all the time to update the list of online
49
// users
50
private ChatOnlineCheck checker = null;
51     private JDialog thisDialog = null;
52
53     // this user's socket information used for sending-receiving chat msgs
54
private ObjectOutputStream oos = null;
55     private Socket socket = null;
56     private SocketReader socketReader = null;
57
58     private static String JavaDoc currentUser = null;
59
60     private Whiteboard wb = null;
61
62  
63     /** Creates new form ChatDialog */
64     public ChatDialog(java.awt.Frame JavaDoc parent, boolean modal)
65         throws ConnectException, IOException {
66
67         super(parent, modal);
68         thisDialog = this;
69         initComponents();
70         initStylesForTextPane();
71
72         wb = MainWindow.getWhiteboard();
73
74         setLang();
75         setColors();
76         setFonts();
77
78         createSocket();
79
80         try {
81             currentUser = wb.getCurrentUser().getID();
82             logonToChat();
83             checker = new ChatOnlineCheck(oos, currentUser);
84             sendQuery();
85             checker.start();
86         } catch (Exception JavaDoc e) {
87             ErrorHandler.show(thisDialog, e);
88         }
89     }
90   
91     /**
92      * setup the text styles for the reply message box
93      */

94     private void initStylesForTextPane() {
95         Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
96
97         regular = conversationTextPane.addStyle("regular", def);
98         StyleConstants.setFontFamily(regular, "SansSerif");
99         StyleConstants.setForeground(regular, Color.RED);
100
101         regularFrom = conversationTextPane.addStyle("regularFrom", def);
102         StyleConstants.setFontFamily(regularFrom, "SansSerif");
103         StyleConstants.setForeground(regularFrom, Color.GREEN);
104
105         bold = conversationTextPane.addStyle("bold", regular);
106         StyleConstants.setForeground(bold, Color.BLACK);
107         StyleConstants.setBold(bold, true);
108
109     }
110
111     /**
112      * create the screen's widgets
113      */

114     private void initComponents() {
115         java.awt.GridBagConstraints JavaDoc gridBagConstraints;
116
117         setTitle("Chat Dialog for " + currentUser);
118         buttonPanel = new javax.swing.JPanel JavaDoc();
119         beepBox = new JCheckBox("Beep");
120         sendButton = new javax.swing.JButton JavaDoc();
121         closeButton = new javax.swing.JButton JavaDoc();
122         mainPanel = new javax.swing.JPanel JavaDoc();
123         jScrollPane1 = new javax.swing.JScrollPane JavaDoc();
124         conversationArea = new javax.swing.JTextArea JavaDoc();
125         conversationTextPane = new JTextPane();
126         jScrollPane2 = new javax.swing.JScrollPane JavaDoc();
127         msgArea = new javax.swing.JTextArea JavaDoc();
128         jScrollPane3 = new javax.swing.JScrollPane JavaDoc();
129         usersList = new javax.swing.JList JavaDoc();
130
131         addWindowListener(new java.awt.event.WindowAdapter JavaDoc() {
132             public void windowClosing(java.awt.event.WindowEvent JavaDoc evt) {
133                 closeDialog(evt);
134             }
135         });
136
137         beepBox.setText("Beep");
138         buttonPanel.add(beepBox);
139         sendButton.setText("Send");
140         buttonPanel.add(sendButton);
141
142         closeButton.setText("Close");
143         buttonPanel.add(closeButton);
144
145         getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH);
146
147         mainPanel.setLayout(new java.awt.GridBagLayout JavaDoc());
148
149         mainPanel.setBorder(new javax.swing.border.EtchedBorder JavaDoc());
150         jScrollPane1.setName("null");
151         jScrollPane1.setMinimumSize(new java.awt.Dimension JavaDoc(400, 200));
152         conversationTextPane.setEditable(false);
153         jScrollPane1.setViewportView(conversationTextPane);
154         jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
155
156         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
157         gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
158         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
159         gridBagConstraints.ipady = 15;
160         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 0, 10, 0);
161         gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
162         mainPanel.add(jScrollPane1, gridBagConstraints);
163
164         int HEIGHT=100;
165         jScrollPane2.setName("null");
166         jScrollPane2.setMinimumSize(new java.awt.Dimension JavaDoc(300, HEIGHT));
167         jScrollPane2.setPreferredSize(new java.awt.Dimension JavaDoc(360, HEIGHT));
168         jScrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
169         msgArea.setColumns(30);
170         msgArea.setLineWrap(true);
171         msgArea.setWrapStyleWord(true);
172         msgArea.setRows(6);
173         jScrollPane2.setViewportView(msgArea);
174
175         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
176         gridBagConstraints.gridx = 0;
177         gridBagConstraints.gridy = 1;
178         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
179         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 0, 0, 7);
180         gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
181         mainPanel.add(jScrollPane2, gridBagConstraints);
182
183         jScrollPane3.setPreferredSize(new java.awt.Dimension JavaDoc(80, HEIGHT));
184         jScrollPane3.setName("null");
185         jScrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
186         jScrollPane3.setMinimumSize(new java.awt.Dimension JavaDoc(80, HEIGHT));
187         jScrollPane3.setMaximumSize(new java.awt.Dimension JavaDoc(80, HEIGHT));
188         usersList.setName("null");
189         usersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
190         jScrollPane3.setViewportView(usersList);
191
192         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
193         gridBagConstraints.gridx = 1;
194         gridBagConstraints.gridy = 1;
195         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
196         gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
197         mainPanel.add(jScrollPane3, gridBagConstraints);
198
199         getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER);
200
201         pack();
202
203         this.addWindowFocusListener(
204             new WindowFocusListener() {
205                 public void windowGainedFocus(WindowEvent ev) {
206                 
207                     if ((checker != null) && (checker.isAlive()))
208                         ; //System.out.println("thread already running");
209
else {
210                         //System.out.println("starting new thread");
211
checker = new ChatOnlineCheck(oos, currentUser);
212                         checker.start();
213     
214                         try {
215                             createSocket();
216                         } catch (Exception JavaDoc x) {
217                             ErrorHandler.show(thisDialog, x);
218                         }
219                     }
220                 }
221
222                 public void windowLostFocus(WindowEvent ev) {
223                 }
224             }
225         );
226
227         sendButton.addActionListener(
228             new ActionListener() {
229                 public void actionPerformed(ActionEvent ev) {
230                     ChatPacket msg = new ChatPacket();
231                     msg.setAction(ChatPacket.SEND_MSG);
232                     ArrayList toList = new ArrayList();
233                     String JavaDoc toUser = (String JavaDoc)usersList.getSelectedValue();
234                     toList.add(toUser);
235                     msg.setToList(toList);
236                     msg.setMessage(msgArea.getText());
237                     msg.setSender(currentUser);
238                     sendMessage(msg);
239                     msgArea.setText("");
240                 }
241             }
242         );
243
244         closeButton.addActionListener(
245             new ActionListener() {
246                 public void actionPerformed(ActionEvent ev) {
247                     thisDialog.hide();
248                 }
249             }
250         );
251
252         setSize(463, 219);
253     }
254     
255     /** Closes the dialog */
256     private void closeDialog(java.awt.event.WindowEvent JavaDoc evt) {
257         setVisible(false);
258         dispose();
259     }
260     
261     
262     /**
263      * append the received chat message onto the window's text
264      * area
265      * @param the chat message to display
266      * @param style the text style to use when drawing
267      */

268     public void appendConversation(ChatPacket msg, Style style) {
269         Document doc = conversationTextPane.getDocument();
270         
271         try {
272             doc.insertString(doc.getLength(), msg.getSender(),
273                 conversationTextPane.getStyle("bold"));
274
275             doc.insertString(doc.getLength(), " : ",
276                 conversationTextPane.getStyle("bold"));
277
278             doc.insertString(doc.getLength(), msg.getMessage(), style);
279
280             doc.insertString(doc.getLength(), newline, style);
281
282
283         } catch (BadLocationException ble) {
284             ErrorHandler.show(thisDialog, ble);
285         }
286     }
287
288     /**
289      * send a chat message to the chat server
290      * @param chatMsg the chat message to send
291      */

292     public void sendMessage(ChatPacket chatMsg) {
293         try {
294             oos.writeObject(chatMsg);
295             oos.flush();
296             if (chatMsg.getAction() == ChatPacket.SEND_MSG)
297                 appendConversation(chatMsg, regularFrom);
298         } catch (IOException e){
299             ErrorHandler.show(thisDialog, e);
300         }
301     }
302
303     /**
304      * create a socket connection to the chat server
305      */

306     public void createSocket()
307         throws IOException {
308
309         socket = new Socket("localhost", 7900);
310         oos = new ObjectOutputStream(socket.getOutputStream());
311         socketReader = new SocketReader(socket, conversationTextPane, usersList);
312         socketReader.start();
313     }
314
315     /**
316      * this class is a thread which runs periodically and reads
317      * messages from the chat server
318      */

319     public class SocketReader extends Thread JavaDoc {
320
321         /** flag which allows us to shut down this thread gracefully */
322         private boolean readingSocket = true;
323
324         /** input socket stream we will read from */
325         private ObjectInputStream ois = null;
326         private Socket socket = null;
327
328         /** window list that we update with query results */
329         private JList usersList = null;
330
331         /** window text pane we update with chat msgs */
332         private JTextPane textPane = null;
333
334         /** build the thread */
335         public SocketReader(Socket socket, JTextPane textPane, JList usersList)
336             throws IOException {
337
338             this.socket = socket;
339             this.textPane = textPane;
340             this.usersList = usersList;
341             ois = new ObjectInputStream(socket.getInputStream());
342         }
343
344         /**
345          * stop the thread gracefully
346          */

347         public void stopRunning() {
348             readingSocket = false;
349         }
350
351         /**
352          * this thread's run() method which runs all the
353          * time to check for chat messages
354          */

355         public void run() {
356             try {
357                 while (readingSocket == true) {
358                     ChatPacket msg = (ChatPacket)ois.readObject();
359                     //System.out.println("this user just got in a message");
360
if (msg.getAction() == ChatPacket.QUERY_USERS) {
361                         //System.out.println("QUERY USERS received");
362
updateUsersList(msg);
363                     } else {
364                         //System.out.println("SEND MSG received");
365
updateMsgArea(msg);
366                         if (beepBox.isSelected())
367                             Toolkit.getDefaultToolkit().beep();
368                     }
369                 }
370             } catch (java.io.EOFException JavaDoc err) {
371                 ErrorHandler.show(thisDialog, err, wb.getLang().getString("chatServerDied"));
372             } catch (Exception JavaDoc e) {
373                 ErrorHandler.show(thisDialog, e);
374             }
375         }
376
377         /**
378          * update the window's chat message area with a chat message
379          * @param msg the chat message to draw
380          */

381         private void updateMsgArea(ChatPacket msg) {
382             //System.out.println(" got a message back will update msg area");
383
appendConversation(msg, regular);
384         }
385
386         /**
387          * update the list of online users
388          * @param the chat message holding the list of online users
389          */

390         private void updateUsersList(ChatPacket msg) {
391
392             String JavaDoc selectedItem = (String JavaDoc)usersList.getSelectedValue();
393             usersList.setListData(msg.getOnlineUsers().toArray());
394             if (selectedItem != null) {
395                 usersList.setSelectedValue(selectedItem, true);
396             }
397         }
398     }
399
400     /**
401      * logon to the chat server by sending a logon message
402      */

403     private void logonToChat() {
404
405         ChatPacket msg = new ChatPacket();
406         msg.setAction(ChatPacket.LOGON);
407         msg.setSender(currentUser);
408         sendMessage(msg);
409     }
410
411     /**
412      * send a query message to the chat server
413      */

414     private void sendQuery() {
415         try {
416             ChatPacket msg = new ChatPacket();
417             msg.setSender(currentUser);
418             msg.setAction(ChatPacket.QUERY_USERS);
419             
420             oos.writeObject(msg);
421             oos.flush();
422         } catch (Exception JavaDoc e) {
423             ErrorHandler.show(thisDialog, e);
424         }
425     }
426
427     /**
428     * This class is run in a separate thread in the
429     * Swing GUi to check for online users
430     */

431     class ChatOnlineCheck extends Thread JavaDoc {
432         private String JavaDoc currentUser = null;
433         private ObjectOutputStream oos = null;
434         private Socket socket = null;
435         private Runnable JavaDoc runnable;
436         private static final int ACT_CHK_TIME = 1000 * 10; //10 seconds
437
private ArrayList alarms=null;
438         private boolean stopRunning=false;
439     
440         /**
441         * this method is called by Swing as it processes
442         * it's event queue which gets populated by the invokeLater()
443         * below
444         */

445         public ChatOnlineCheck(ObjectOutputStream oos, String JavaDoc currentUser) {
446             this.oos = oos;
447             this.currentUser = currentUser;
448
449             runnable = new Runnable JavaDoc() {
450                 public void run() {
451                     System.out.println("ChatOnlineCheck running ");
452                 }
453             };
454         }
455
456         /**
457         * stop this thread from continuing
458         */

459         public void stopRunning() {
460             stopRunning = true;
461         }
462
463         /**
464          * the main entry point for this Thread, an infinite loop that
465          * wakes up every so often (ACT_CHK_TIME), does some checking to
466          * see if we need to process some activities, and then queue a
467          * request to Swing's internal event queue processing mechanism,
468          * then go back to waiting for the next wakeup.
469         */

470         public void run() {
471             try {
472                 ChatPacket msg = new ChatPacket();
473                 msg.setSender(currentUser);
474                 msg.setAction(ChatPacket.QUERY_USERS);
475             
476                 while (stopRunning == false) {
477                     sleep(ACT_CHK_TIME);
478                 
479                     oos.writeObject(msg);
480                     oos.flush();
481                     SwingUtilities.invokeLater(runnable);
482                 }
483             } catch (Exception JavaDoc e) {
484                 ErrorHandler.show(thisDialog, e);
485             }
486         }
487     }
488     /**
489      * set the screen's text fields to some language
490      */

491     public final void setLang() {
492         setTitle(wb.getLang().getString("chatDialog"));
493         sendButton.setText(wb.getLang().getString("send"));
494         closeButton.setText(wb.getLang().getString("close"));
495         beepBox.setText(wb.getLang().getString("beep"));
496     }
497
498     /**
499      * set the screen's colors
500      */

501     public final void setColors() {
502     }
503
504     /**
505      * set the screen's fonts
506      */

507     public final void setFonts() {
508         beepBox.setFont(MainWindow.LABEL_FONT);
509         sendButton.setFont(MainWindow.LABEL_FONT);
510         closeButton.setFont(MainWindow.LABEL_FONT);
511     }
512
513 }
514
Popular Tags