Hello,
I have a Client/Server program where the Server sends a string with a time delay using a Timer object to the Client.
The Client has a JFrame with a JTextArea for display. When I test the Client program, I ran into two issues:
a) Nothing ever shows up on the JTextArea.
b) When I test Client's terminal, the output is accurate.
So, the problem seems to be in the run() method where it reads from the Server and does a "setText()" on the JTextArea. I use setText because I want the program to clear the previous text in the textarea and add the new string sent by the server.
If I use append(), the program works fine, but I want the previous text to be cleared.
Any help would be much appreciated.
The Client program is as below.
Thank you!
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChatClients extends JFrame implements Runnable
{
private Socket socket = null;
private BufferedReader reader = null;
private PrintWriter writer = null;
private Thread thread;
private JTextField field;
private JTextArea area;
private JButton button;
private JScrollPane pane;
private String line = "";
public ChatClients(String serverName, int serverPort)
{
super("Client");
setLayout (new FlowLayout());
field = new JTextField (20);
area = new JTextArea (20, 50); // rows, columns = height, width
button = new JButton ("Send to Server");
area.setLineWrap(true);
area.setEditable(false);
area.setFont (new Font ("Courier New", Font.PLAIN, 18));
area.setForeground (Color.BLUE);
area.setBackground (Color.LIGHT_GRAY);
pane = new JScrollPane(area);
add(pane);
add(field);
add (button);
button.addActionListener (
new ActionListener()
{
public void actionPerformed (ActionEvent event)
{
writer.println (field.getText());
area.append ("CLIENT : " + field.getText() +"
");
field.setText("");
}
}
);
System.out.println("Establishing connection. Please wait ...");
try
{
socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
start();
}
catch(UnknownHostException uhe)
{
System.out.println("Host unknown: ");
}
catch(IOException ioe)
{
System.out.println("Unexpected exception: ");
}
thread = new Thread (this);
thread.start();
setSize (1000, 800);
setVisible (true);
}
public void run ()
{
boolean flag = true;
while (flag == true)
{
try
{
line = reader.readLine();
System.out.println (line);
gohere();
}
catch (Exception e)
{}
}
}
public void gohere()
{
SwingUtilities.invokeLater(
new Runnable()
{
public void run()
{
area.setText(" " + line + "\n");
}
}
);
}
public void start() throws IOException
{
reader = new BufferedReader (new InputStreamReader (socket.getInputStream()));
writer = new PrintWriter (socket.getOutputStream(), true);
}
public static void main(String args[])
{
ChatClients client = new ChatClients("localhost", 2000);
}
}