26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 17 Networking 1051<br />

244 // when received, display new messages in messageArea<br />

245 public void messageReceived( String from, String message )<br />

246 {<br />

247 // append message using MessageDisplayer and<br />

248 // invokeLater, ensuring thread-safe access messageArea<br />

249 SwingUtilities.invokeLater(<br />

250 new MessageDisplayer( from, message ) );<br />

251<br />

252 } // end method messageReceived<br />

253<br />

254 } // end MyMessageListener inner class<br />

255<br />

256 // MessageDisplayer displays a new messaage by<br />

257 // appending the message <strong>to</strong> the messageArea JTextArea. This<br />

258 // Runnable object should be executed only on the Event<br />

259 // thread, because it modifies a live Swing component.<br />

260 private class MessageDisplayer implements Runnable {<br />

261<br />

262 private String fromUser;<br />

263 private String messageBody;<br />

264<br />

265 // MessageDisplayer construc<strong>to</strong>r<br />

266 public MessageDisplayer( String from, String body )<br />

267 {<br />

268 fromUser = from;<br />

269 messageBody = body;<br />

270 }<br />

271<br />

272 // display new message in messageArea<br />

273 public void run()<br />

274 {<br />

275 // append new message<br />

276 messageArea.append( "\n" + fromUser + "> " +<br />

277 messageBody );<br />

278<br />

279 // move caret <strong>to</strong> end of messageArea <strong>to</strong> ensure new<br />

280 // message is visible on screen<br />

281 messageArea.setCaretPosition(<br />

282 messageArea.getText().length() );<br />

283 }<br />

284<br />

285 } // end MessageDisplayer inner class<br />

286 }<br />

Fig. Fig. Fig. 17.20 17.20 ClientGUI subclass of JFrame for presenting a GUI for viewing and<br />

sending chat messages (part 6 of 6).<br />

ClientGUI uses a MessageManager (line 41) <strong>to</strong> handle all communication with<br />

the chat server. Recall that MessageManager is an interface and therefore allows ClientGUI<br />

<strong>to</strong> use any MessageManager implementation without the need <strong>to</strong> change any<br />

code in ClientGUI. Class ClientGUI also uses a MessageListener (line 44) <strong>to</strong><br />

receive incoming messages from the MessageManager.<br />

The ClientGUI construc<strong>to</strong>r (lines 47–183) takes as an argument the Message-<br />

Manager for communicating with DeitelMessengerServer. Line 52 sets the Cli-

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!