Use of SwingWorker to do complex tasks in background

安稳与你 提交于 2019-11-28 11:42:56

问题


I am having a GUI of login screen. Whenever i press the login button the user name and password is checked against entry in an online mysql database,i'm extracting all this information from database in actionPerformed() method of the login button.Problem is while program is fetching data from database the GUI freezes.I googled my problem and found that i should use SwingWorker but being a newbie i didn't get how to use SwingWorker for my purpose.


回答1:


First of all, declare a member variable in your class (it could be in your GUI class) of type SwingWorker like this:

private SwingWorker<Boolean, Void> backgroundProcess;

Then initialize the variable in your initialization code (constructor, onShow method event handler, etc) like this:

    backgroundProcess = new SwingWorker<Boolean, Void>() {

        @Override
        protected Boolean doInBackground() throws Exception {
            // paste the MySQL code stuff here
        }

        @Override
        protected void done() {
            // Process ended, mark some ended flag here
            // or show result dialog, messageBox, etc      
        }
    };

Then, in your actionPerfomed method, call the SwingWorker's execute method:

    backgroundProcess.execute();

If done correctly, the GUI shouldn't freezee after the button press event




回答2:


This simple example extends SwingWorker<Icon, Void> to fetch an Icon with Void intermediate results. Similarly, yours might extend SwingWorker<DataSource, Void> to fetch a DataSource.



来源:https://stackoverflow.com/questions/11255925/use-of-swingworker-to-do-complex-tasks-in-background

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!