Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Java Swing GUI, how can I run a Server Socket in the background and still use the GUI?

I have a basic server working but I want to be able to press a button in the GUI to run said server.

Currently, when I press the button to run the server, the button stays pressed and the rest of the GUI is inaccessible until I force stop it in Netbeans. I want to include buttons to stop the server etc so I want to know how I can have the server code run in the background whilst interacting with the GUI for anything else.

How can I achieve this in the GUI?

like image 806
Rookie Avatar asked Dec 02 '25 05:12

Rookie


2 Answers

Don't block the EDT (Event Dispatch Thread). Run the server on a Thread. See Concurrency in Swing for more details.


Mentioned in a comment, but see also this (very much) related example of providing a Swing GUI for a server & client.

enter image description here

like image 159
Andrew Thompson Avatar answered Dec 03 '25 20:12

Andrew Thompson


You should use Thread class for this purpose.
Implement runnable interface in your main class, then override run() method. Put the codes you want them to be done when the button is pressed in run() method. Then in the button ActionListener write this code:

new Thread(this).start();

This will execute the code in a different 'thread'.

like image 26
mehrmoudi Avatar answered Dec 03 '25 22:12

mehrmoudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!