Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution trapped inside the button

I have a method called inside a button that run almost an infinite loop. I can't access the other buttons while running this method.

How I make to free the interface to access other buttons while running this method?

//methods inside the button
this.setCrawlingParameters();
webcrawler = MasterCrawler.getInstance();
webcrawler.resumeCrawling(); //<-- the infinite loop method
like image 711
Renato Dinhani Avatar asked Sep 20 '26 05:09

Renato Dinhani


2 Answers

you need to use a SwingWorker

The way Swing works is that it has one main thread, the Event Dispatch Thread(EDT) that manages the UI. In the Swing documentation, you will see that it is recommended to never to long-running tasks in the EDT, because, since it manages the UI, if you do something computationally heavy your UI will freeze up. This is exactly what you are doing.

So you need to have your button invoke a SwingWorker so the hard stuff is done in another thread. Be careful not to modify UI elements from the SwingWorker; all UI code needs to be executed in the EDT.

If you click the link for SwingWorker, you will see this:

Time-consuming tasks should not be run on the Event Dispatch Thread. Otherwise the application becomes unresponsive. Swing components should be accessed on the Event Dispatch Thread only

as well as links to examples on how to use a SwingWorker.

like image 65
hvgotcodes Avatar answered Sep 21 '26 20:09

hvgotcodes


Start a new Thread:

// In your button:
Runnable runner = new Runnable()
{
    public void run()
    {
         setCrawlingParameters(); // I removed the "this", you can replace with a qualified this
         webcrawler = MasterCrawler.getInstance();
         webcrawler.resumeCrawling(); //<-- the infinite loop method
    }
}
new Thread(runner, "A name for your thread").start();
like image 38
Martijn Courteaux Avatar answered Sep 21 '26 19:09

Martijn Courteaux



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!