chrupeq
chrupeq

Reputation: 15

How to handle two different events

I am making a simple chat GUI and I have written both a server and GUI client and I can send a message from the client GUI to the server.

My problem is with receiving message from a server on frame. When I use an infinite loop the frame is locked. I don't know how I should split the thing to get any message displayed on JTextArea. My question is: Is there any way to split frame to handle the 'send' and 'receive' information from a server?

My GUI consists of a JTextField, JTextArea and JButton.

When press the JButton the text from JTextField is sent to the server by:

String u = jTextField.getText(); 
out.writeUTF(u);

But I don't know what I should do to get JTextArea lessen all time for coming information by:

msg = in.readUTF();
jta.append(msg + "\n");

//

Should the thread be a class or component in GUI class because i have made thread evrything seems to be working but massage don't apear on jTextField. I made thread like in server I did in same file but is not working:

    class bacgroundTask extends Thread{
static String msg;
static JTextArea jta;
static DataInputStream in;
public void run(){
        while(true){
            try{
            msg = in.readUTF();
            jta.append(msg + "\n");
            }
            catch(IOException ioe){}}}}

//

Hi it's again me i try use the invokelater method but the frame frezze when is executed i can't clik send button or type in text in jtextfield. Could any body explain me a bit more about them methods and are they right in my case.

I have tried with and without while stetment.

       SwingUtilities.invokeLater(
        new Runnable(){
            public void run(){
                while(true){
                try{
                    msg = in.readUTF();
                    jta.append(msg + "\n");
                    jta.revalidate();
                }
                catch(IOException ioe){

                }}}});

Upvotes: 0

Views: 108

Answers (2)

Kylar
Kylar

Reputation: 9334

You shouldn't update the GUI components in a background thread. Try using SwingUtilities.invokeLater, and don't forget to use something like revalidate() on your text area.

Upvotes: 1

SLaks
SLaks

Reputation: 887797

You need to run an infinite receive loop on a background thread.

Upvotes: 1

Related Questions