Use of SwingWorker to do complex tasks in background

前端 未结 2 984
半阙折子戏
半阙折子戏 2020-12-21 21:34

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

2条回答
  •  时光取名叫无心
    2020-12-21 21:54

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

    private SwingWorker backgroundProcess;
    

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

        backgroundProcess = new SwingWorker() {
    
            @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

提交回复
热议问题