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.
Asked
Active
Viewed 2,705 times
2 Answers
3
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

higuaro
- 15,730
- 4
- 36
- 43
-
+1 for a helpful outline, but I don't understand using `Boolean`. Wouldn't a `Connection` or `DataSource` be more appropriate. – trashgod Jun 29 '12 at 10:07
0
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
.
-
You mean that i have to fetch data from DB in doInBackground() method and call the execute() method when user clicks on the login button. – kaysush Jun 29 '12 at 04:20
-
Yes; `done()` executes on the EDT, so you can update you GUI once you get a connection, – trashgod Jun 29 '12 at 04:24
-
how can in get value returned from doInBackground() in done() method? I want to show a new JFrame if it reurns true and show an error message if it returns false.Do i need another EDT in done to show new frame? – kaysush Jun 29 '12 at 04:35
-
1@SushilKumar the easy way is to declare a member variable inside the `SwingWorker` declaration (after the `new SwingWorker
() {` line), you can reference that variable in both doInBackground and done methods – higuaro Jun 29 '12 at 04:54 -
@h3nr1x is correct; the example cited includes an `ImageIcon` member variable. – trashgod Jun 29 '12 at 10:05