Search code examples
javaswingjtextareaserversocketevent-dispatching

Append to JTextArea


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

Solution

  • 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.