Append to JTextArea

277 Views Asked by At

I am making server side app, but when I am trying to append text to the JTextarea, it's not working. It prints, however, to the console.

It worked fine until I added the line serverSocket.accept().

Here is my code:

try { 
    serverSocket=new ServerSocket(4545); 
    LogOutput.append("Seccessfuly connected\n" );  
    System.out.println("Seccessfuly connected\n" );              

    StartButon.setEnabled(false);

    while(true){
        LogOutput.append("waiting for client\n" );
        System.out.println("waiting for client\n" ); 

        serverSocket.accept();
        LogOutput.append("Client connected to server\n" );               
    }
}
catch(Exception e){
    LogOutput.append("cannot establish connection : "+ e +"\n" );
    StartButon.setEnabled(true);
}
2

There are 2 best solutions below

0
On BEST ANSWER

You're completely blocking the Swing event thread or EDT. Get most of that code, starting with the while (true) block onto a background thread if you want your Swing GUI to function in conjunction with a long-running process. Please read the Concurrency in Swing tutorial to see why this matters, and how to solve this issue with a SwingWorker object.

0
On

From the given code snippet and your question it seems you are looking for

Client connected to server\n

to be added to your textArea.

serverSocket.accept();
LogOutput.append("Client connected to server\n" );       

Once you say serverSocket.accept() now it will wait for client connection to arrive, unless there is some client your next line of code is not going to be executed. serverSocket.accept is blocking method, Start your client program and your server will start processing next line of code.

From the docs

public Socket accept() throws IOException

Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.