I am making a Swing application, and I have a Runnable class that runs a thread, and the thread makes an HTTP request what is the best way to know when the thread finished?
private void loginMouseClicked(java.awt.event.MouseEvent evt) {
login.setEnabled(false);
loading.setVisible(true);
DoLogin log = new DoLogin(user.getText(), pass.getPassword().toString());
Thread t = new Thread(log);
t.start();
loading.setVisible(false);
login.setEnabled(true);
}
I would like to move the last 2 lines of that method to another method that gets fired off when the thread completes. How can I do this?
Use a SwingWorker. Do the login in the
doInBackground()method, and put your other two lines of code in thedone()method.It is important to do it this way, rather than simply adding the additional actions to perform to the end of the login thread, or spawning yet another thread for them, because they update your UI and so you want to perform them on the Swing UI thread.
SwingWorker‘sdone()method will be invoked on the Swing UI thread.