简体   繁体   中英

Java - How can I append to a jTextArea from a socket?

So, I decided to try to work on a ServerSocket/Socket instant messenger to get familiarized with how to use ServerSockets and Sockets. I am currently still working on the server side of the application, and am having trouble getting a jTextArea on the GUI to update with information sent from a client program.

Here is my code:

For the Socket side of things (ServerSocket class):

while (shouldRun) {
    inputMessage = (String)input.readObject();
    new jMessengerServerGUI().updateFeed(inputMessage);
    System.out.println(inputMessage);
}

And for the GUI (jMessengerServerGUI class):

public void updateFeed(String updateMessage) {
    txtServerFeed.append(updateMessage);
    System.out.println(updateMessage);
}

The methods are in separate classes, where the string inputMessage is received and sent flawlessly and is printed out in the console. The issue comes with updating the jTextArea txtServerFeed.

How can I best achieve writing to the TextArea when called from an outside class?

You Need to make your Application Multi-threaded. Where Server & Socket works separate thread rather than UI-Thread;

You can See that example: https://github.com/khirulbasher/Multithreaded-Server-Client

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