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);
    }
}

Just to clarify what you said: if you append the text to the textarea it works ok, but change that one method to setText then it doesn't?

Hello James,

Yes - precisely. Initially, with setText(), I saw some charcters come and go because of the Timer. I changed the settext to be under a separate thread (the gohere() method) and now I see nothing at all.

Thank you!

OK, so actually it's nothing to do with setText vs update, it's to do with moving the Swing calls into a different thread?
Doing the text area update on the swing thread is good practice, so don't change that.
You don't say how the test works - do you send a nuber of lines very quickly, or is there a multi-second pause between lines? If it's the former then maybe your code is working correctly, and you could put a sleep between sending lines to confirm.
You could also try an invokeAndWait to force an immediate update, rather than waiting for an invokeLater

Hello James,

Thank you for your reply.

The Server sends text with a two second delay. I figured that should be enough to display the text in the textarea. I tried increasing the delay to five seconds and I still do not see the text in the textarea. Also, tried Thread.sleep on both client and server, and it still gives me nothing in the textarea.

Here is the server code:

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class ChatServer implements Runnable
{
    private Socket          socket   = null;
    private ServerSocket    server   = null;
    private Thread thread = null;
    private int ID = 0;
    private  ArrayList <PrintWriter> list = new ArrayList  <PrintWriter> ();

    public ChatServer(int port)
    {

        try
        {

            System.out.println("Binding to port " + port + ", please wait  ...");

            server = new ServerSocket(port);

            System.out.println("Server started: " + server);

            System.out.println("Waiting for a client ...");

        }

        catch(IOException ioe)
        {
            System.out.println(ioe);
        }

        thread = new Thread(this);

        thread.start();

    }

    public void run()
    {
        while (true)
        {
            try
            {
                socket = server.accept();
                ID++;
                System.out.println("Client:" + ID + " Accepted " + socket);
                ChatServerThread t = new ChatServerThread (socket, ID);
                t.start();
            }
            catch(IOException ioe)
            {
                System.out.println(ioe);
            }
        }
    }

    public static void main(String args[])
    {
        ChatServer server = new ChatServer(2000);
    }

    private class ChatServerThread extends Thread
    {
        private Socket socket = null;
        private BufferedReader  reader =  null;
        private PrintWriter     writer = null;
        private Thread t;
        private int id;
        private String line;
        private Timer timer;
        private String x = "";
        private int i = 0;
        private String a[] = {"  @..@", " (\\--/) ", "(.>__<.)", "^^^  ^^^", ""};

        public ChatServerThread (Socket s, int ID)
        {
            super("Server");
            socket = s;
            id = ID;

            try
            {
                open();
            }
            catch (IOException e)
            {}
            list.add(writer);
            writer.println (id);
            timer = new Timer (2000,
                new ActionListener()
                {
                    public void actionPerformed (ActionEvent e)
                    {
                        draw();
                    }
                }

            );
            timer.start();

            t = new Thread (this);
            t.start();
        }

        public void draw()
        {
            if (!a[i].equals(""))
            {
                x += a[i] +"\n";

                i++;

                writer.println(x);

            }
        }


        public void run ()
        {
            boolean flag = true;
            while (flag == true)
            {
                try
                {
                    line = reader.readLine();
                    if (line.equals("cat"))
                    {
                        timer.stop();
                        writer.println("Correct");
                    }

                }
                catch (Exception e)
                {}
            }

        }

        public void open() throws IOException
        {
            reader = new BufferedReader (new InputStreamReader (socket.getInputStream()));
            writer  = new PrintWriter (socket.getOutputStream(), true);
        }

    }

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.