Search code examples
javaswingswingworker

Login in SwingWorker


I have a class which extends SwingWorker<Void, Void>. In it's background thread I was supposed to do login, if successful changing layout and adding new panels to frame. So Swing worker do following 3 tasks:

  1. Login
  2. Change layout
  3. Add/remove panels.

So I wrote this function in doInBackground() method. But what happens here is this 3 methods are always executed, no matter login is successful or not. I want to stop executing worker if login fails. I tried cancel() method but it did not worked. How can I do this in proper way? What could be the proper way to do login task in SwingWorker?


Solution

  • The second and third steps must NOT be done in the doInBackground() method, since they use Swing components and must thus be done in the event dispatch thread. They must be done in the done() method, if the login was successful.

    So your SwingWorker should rather be a SwingWorker<Boolean, Void>. The doInBackground() method should return true if the login was successful, and false if not:

    SwingWorker<Boolean, Void> loginWorker = new SwingWorker<Boolean, Void>() {
        protected Boolean doInBackground() {
            return login();
        }
    
        protected void done() {
            try {
                boolean loginSuccessful = get();
                if (loginSuccessful) {
                    updateGUI();
                }
            }
            catch (Exception e) {
                displayErrorMessage(e);
            }
        }
    };