import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
public class Chat extends JApplet implements Runnable, ActionListener, ListSelectionListener {
private static final int PORT = 1080;
private Socket socket;
private BufferedReader in;
private PrintStream out;
private JTextField inputfield;
private JTextArea outputarea;
private Thread thread;
private String recipient ="";
private JList userlist;
private JScrollPane scrollpane;
private JLabel msghere;
public void run()
{
String line;
try
{
while(true)
{
line = in.readLine();
if(line!=null){
outputarea.append(line + "--> " + recipient +'\n' );
outputarea.setCaretPosition(outputarea.getDocument().getLength());
}
}
} catch (IOException e) { say("Verbindung zum Server abgebrochen"); }
}
public void init()
{
userlist = new JList();
userlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
userlist.addListSelectionListener(this);
userlist.setBorder(BorderFactory.createEtchedBorder());
userlist.setFixedCellWidth(100);
userlist.setSelectionForeground(Color.BLACK);
userlist.setSelectionBackground(Color.WHITE);
inputfield = new JTextField();
inputfield.addActionListener(this);
outputarea = new JTextArea();
outputarea.setFont( new Font("Dialog", Font.PLAIN, 12));
outputarea.setEditable(false);
inputfield.setBackground(Color.white);
outputarea.setBackground(Color.white);
scrollpane = new JScrollPane(outputarea);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollpane.setWheelScrollingEnabled(true);
msghere = new JLabel("Nachricht: ");
msghere.setPreferredSize(new Dimension(80,20));
inputfield.setPreferredSize(new Dimension(500,20));
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(msghere);
panel.add(inputfield);
setLayout(new BorderLayout());
add("West", userlist);
add("South",panel);
add("Center", scrollpane);
setBackground(Color.lightGray);
setForeground(Color.black);
}
public void start()
{
try
{
socket = new Socket(this.getCodeBase().getHost(), PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintStream(socket.getOutputStream());
} catch (IOException e)
{
this.showStatus(e.toString());
say("Verbindung zum Server fehlgeschlagen!");
System.exit(1);
}
say("Verbindung zum Server aufgenommen...");
if (thread == null)
{
thread = new Thread(this);
thread.start();
}
}
public void stop()
{
try
{
socket.close();
} catch (IOException e)
{
this.showStatus(e.toString());
}
if ((thread !=null) && thread.isAlive())
{
thread = null;
}
}
public void actionPerformed(ActionEvent e)
{
out.println(inputfield.getText());
inputfield.setText("");
}
public void say(String msg)
{
outputarea.append("*** "+msg+" ***\n");
}
public void valueChanged(ListSelectionEvent arg0) {
int index = userlist.getSelectedIndex();
if (index != -1) {
recipient = (String)userlist.getSelectedValue();
}
}
}