使用SwingWorker在后台执行复杂的任务 [英] Use of SwingWorker to do complex tasks in background
问题描述
我正在使用登录屏幕的GUI。每当我按下登录按钮时,都会检查用户名和密码以防在在线mysql数据库中输入,我在登录按钮的actionPerformed()方法中从数据库中提取所有这些信息。问题是当程序从数据库中获取数据时GUI冻结。我搜索了我的问题,发现我应该使用SwingWorker,但作为一个新手,我没有得到如何使用SwingWorker为我的目的。
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.
推荐答案
首先,在类中声明一个成员变量(可能在你的GUI类中),类型为 SwingWorker
,如下所示:
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;
然后在初始化代码(构造函数,onShow方法事件处理程序等)中初始化变量,如下所示:
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
}
};
然后,在 actionPerfomed
方法中,调用 SwingWorker
的执行方法:
Then, in your actionPerfomed
method, call the SwingWorker
's execute method:
backgroundProcess.execute();
如果操作正确,按钮按下事件后GUI不应该冻结
If done correctly, the GUI shouldn't freezee after the button press event
这篇关于使用SwingWorker在后台执行复杂的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!