/** This class is responsible for storing and displaying the chat * * @author Kristof Friedrichsen * @author Ryan Mann * @author Bob Free * @author Pat O'Neill * @version December 15, 2006 */ package chutesladder; import java.awt.BorderLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class Chat extends JPanel implements Runnable{ public JTextArea chatH; JTextField say; JButton send; JScrollPane paneCh; public String chatHistory; public static String host = "localhost"; public static Integer port = 2699; public String titleName = ""; protected BufferedReader in; protected PrintWriter out; protected Thread listener; public Chat (String title, InputStream iin, OutputStream iout) { this.in = new BufferedReader (new InputStreamReader (iin)); this.out = new PrintWriter ( new OutputStreamWriter(iout)); titleName = title; chatH = new JTextArea("", 8, 22); paneCh = new JScrollPane(chatH); chatH.setEditable(false); paneCh.setAutoscrolls(true); paneCh.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); chatH.setLineWrap(true); chatHistory = new String("Say something..."); /* The key listener is responsible to display the written text in the * chat box after pressing enter */ say = new JTextField(20); say.addKeyListener ( new KeyAdapter() { public void keyPressed(KeyEvent e){ if(e.getKeyCode() == KeyEvent.VK_ENTER) { String statement = titleName + say.getText(); out.println (statement); out.flush (); say.setText (""); } } } ); say.requestFocus (); listener = new Thread (this); listener.start (); setLayout(new BorderLayout()); add(BorderLayout.NORTH, paneCh); add(BorderLayout.CENTER, say); //add(BorderLayout.SOUTH, send); } public void run () { try { while (true) { String line = in.readLine (); //if ( !line.matches ( "\\S") ) { chatH.append (line + "\n"); chatH.setCaretPosition( chatH.getDocument().getLength() ); } } } catch (IOException ex) { ex.printStackTrace (); } finally { listener = null; say.setVisible (false); validate (); out.close (); } } }