Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GUI, need to pause a method without freezing GUI aswell

I know that this problem is caused by the sleep or wait calling on the main thread and that the answer on how to solve this will be to put the method into a seperate thread and then make that thread sleep. But the code is a mess and don't really have the time to sort it out and split it up into separate threads and was wondering if there is any other way of doing this? Even if it is not the cleanest or most common practice for working with GUIs. I only need about a seconds pause from the method.

like image 334
pie154 Avatar asked Aug 24 '26 23:08

pie154


2 Answers

You can't do it without creating a separate thread. Creating a thread in Java is easy. The only thing to pay attention to is that you can only touch the UI through the main thread. For this reason you need to use something like SwingUtilities.invokeLater().

like image 82
kgiannakakis Avatar answered Aug 26 '26 12:08

kgiannakakis


It is not possible to sleep on an event thread and not cause a GUI freeze. However in Swing, the event thread is created and managed behind the scenes - you main thread (the one originating from main() method) is not the event thread.

So, you can safely sleep on your main thread.

like image 42
pajton Avatar answered Aug 26 '26 12:08

pajton



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!