开发者

SwingWorker in Java (beginner question)

开发者 https://www.devze.com 2022-12-23 21:51 出处:网络
I am relatively new to multi-threading and want to execute a background task using a Swingworker thread - the method that is called does not actually return anything but I would like to be notified wh

I am relatively new to multi-threading and want to execute a background task using a Swingworker thread - the method that is called does not actually return anything but I would like to be notified when it has completed.

From all the tutorials that I have seen online about using SwingWorkers are created such as

new SwingWorker<String, Void&开发者_JAVA百科gt;; 

Would declaring mine as Void, Void be suitable as there is no data being returned?

The code I have so far doesn't appear to be working:

private void crawl(ActionEvent evt)
{
    try
    {
    SwingWorker<Void, Void> crawler = new SwingWorker<Void, Void>()
    {
        @Override
        protected Void doInBackground() throws Exception
        {
            Discoverer discover = new Discoverer();
            discover.crawl();
            return null;
        }

        @Override
        protected void done()
        {
            JOptionPane.showMessageDialog(jfThis, "Finished Crawling", "Success", JOptionPane.INFORMATION_MESSAGE);
        }

    };
    crawler.execute();
    }
    catch (Exception ex)
    {
         JOptionPane.showMessageDialog(this, ex.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
    }
}

Any feedback/advice would be greatly appreciated as multi-threading is a big area of programming that I am weak in.


The code seems ok... It should work. Maybe the crawl method never finishes... What happens if you debug the code and have it run until the line where you return null and see if the crawl method ever finishes...


I would recommend monitoring the status of your crawl method (does it ever finish?) as well as wrapping it within a try { ... } catch block WITHIN your doInBackground. Either that or call "get()" from your done method. Either way should allow you to catch any exceptions that are thrown during crawling.

0

精彩评论

暂无评论...
验证码 换一张
取 消