Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

java - Use of SwingWorker to do complex tasks in background

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...