The easiest way would be to start a new thread that can run the client network loop.
Create a class that implements 'Runnnable' and then create a new Thread to run that class. That class's 'run()' method should loop and receive messages.
DatagramSocket
is thread-safe, so you don't need to worry about accessing it from two separate threads (writing from the GUI thread, reading from the receiving thread).
However, the JTextArea
and other GUI components are different. They can only be modified from the GUI thread. So you can't append to the 'JTextArea' from the receiver thread.
The easiest way to pass data to the GUI thread (from the receiver thread) would be like this.
SwingUtilities.invokeLater(new sendString(client, receivedMessage);
This requires a second new Runnable
class sendString
. The Runnable
class's run()
method can then perform the update, as invokeLater
will cause it to be run by the GUI thread. client
should be a reference to your DatagramClient
instance.
client.jta.append(receivedMessage);