简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM